zoukankan      html  css  js  c++  java
  • 剑指offer04-重建二叉树

    输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

    思路:前序遍历,第一个节点为二叉树root;中序遍历,左中右,root左边为左子树元素,右边为右子树元素;

    根据前序辨认出中间节点,再根据中序遍历和中间节点划分左子树和右子树;递归;

    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
            TreeNode*root=construct(pre,0,pre.size()-1,vin,0,vin.size()-1);
            return root;
        }
        TreeNode* construct(vector<int>pre,int pre_left,int pre_right,vector<int>vin,int vin_left,int vin_right)
        {
            TreeNode*head=new TreeNode(pre[pre_left]);
            for(int i=vin_left;i<=vin_right;i++)
            {
                if(vin[i]==pre[pre_left])
                {
                    if((i-vin_left)!=0)
                    head->left=construct(pre,pre_left+1,pre_left+i-vin_left,vin,vin_left,i-1);
                    if((vin_right-i)!=0)
                    head->right=construct(pre,pre_left+i-vin_left+1,pre_right,vin,i+1,vin_right);
                    
                }
                
            }
            return head;
        }

  • 相关阅读:
    背水一战 Windows 10 (90)
    背水一战 Windows 10 (89)
    背水一战 Windows 10 (88)
    背水一战 Windows 10 (87)
    背水一战 Windows 10 (86)
    背水一战 Windows 10 (85)
    背水一战 Windows 10 (84)
    背水一战 Windows 10 (83)
    背水一战 Windows 10 (82)
    背水一战 Windows 10 (81)
  • 原文地址:https://www.cnblogs.com/trouble-easy/p/12957923.html
Copyright © 2011-2022 走看看