首页 > 代码库 > leetcode-Construct Binary Tree from Preorder and Inorder Traversal

leetcode-Construct Binary Tree from Preorder and Inorder Traversal

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 {
private:
    TreeNode *root;
    vector<int> myPreOrder;
    vector<int> myInOrder;
public:

    TreeNode *createTree(TreeNode *root,int pre,int in,int lenth)
    {
        int l,r,rootPos;
        if(lenth<=0)
            root=NULL;
        else
        {
            //新结点
            root=new TreeNode(myPreOrder[pre]);
            
            //找根
            for(int i=in;i<=in+lenth-1;i++)
                if(root->val==myInOrder[i])
                    rootPos=i;
            
            //子树长
            l=rootPos-in;
            r=lenth-l-1;
            
            //建子树
            root->left=createTree(root->left,pre+1,in,l);
            root->right=createTree(root->right, pre+1+l,rootPos+1,r);
        }
        
        return root;
    }
    
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        if(preorder.size()<=0) return NULL;
        
        //复制
        myPreOrder=preorder;
        myInOrder=inorder;
        
        //建树
        root=createTree(root,0,0,preorder.size());
        return root;
    }
};


leetcode-Construct Binary Tree from Preorder and Inorder Traversal