zoukankan      html  css  js  c++  java
  • 105. Construct Binary Tree from Preorder and Inorder Traversal (Tree; DFS)

    Given preorder and inorder traversal of a tree, construct the binary tree.

    Note:
    You may assume that duplicates do not exist in the tree.

    class Solution {
    public:
        TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
            root = NULL;
            if(inorder.empty()) return root;
            root = new TreeNode(0);
            buildSubTree(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1,root);
            return root;
            
        }
        void buildSubTree(vector<int> &preorder, vector<int> &inorder, int preStartPos, int preEndPos,int inStartPos, int inEndPos, TreeNode * currentNode) //对于树的递归遍历,如果涉及数组,必定参数中要传递start,end,指明当前子树来源于数组的哪一部分
        {
            currentNode->val = preorder[preStartPos]; //前序遍历的第一个为根节点
            
            //find root position in inorder vector
            int inRootPos;
            for(int i = inStartPos; i <= inEndPos; i++)
            {
                if(inorder[i] == preorder[preStartPos])
                {
                    inRootPos = i;
                    break;
                }
            }
            
            //分别递归处理左子树和右子树
            //left tree:是总序遍历中根节点所在位置之前的部分,对应前序遍历根节点之后相同长度的部分
            int newPrePos = preStartPos+max(inRootPos-inStartPos, 0);
            if(inRootPos>inStartPos)
            {
                currentNode->left = new TreeNode(0);
                buildSubTree(preorder,inorder,preStartPos+1, newPrePos,inStartPos,inRootPos-1,currentNode->left); //递归调用时,要传递新的start,end
            }
            //right Tree:是中序遍历根节点所在位置之后的一部分,对应前序遍历从末尾开始相同的长度
            if(inRootPos < inEndPos)
            {
                currentNode->right = new TreeNode(0);
                buildSubTree(preorder,inorder,newPrePos+1, preEndPos,inRootPos+1,inEndPos,currentNode->right); //递归调用时,要传递新的start,end       
            }
         
        }
    private:
        TreeNode* root;
    };
  • 相关阅读:
    8) linux安装samba服务器
    7) k8s获取apiversion下面的对应可用资源
    4) cobbler自动安装linux
    3) KVM命令--使用篇(1)
    2) 各种开源环境自动部署脚本
    1) nginx编译安装
    扁平式小清新导航
    互联网公司常用水平导航(二级导航)
    水平导航-三级导航-切换流畅
    简约蓝色系导航(三级导航)
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854520.html
Copyright © 2011-2022 走看看