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;
};

 

posted on 2015-10-04 14:24  joannae  阅读(147)  评论(0编辑  收藏  举报

导航