[leetcode] Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder 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> &inorder, vector<int> &postorder) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(inorder.size()==0)
            return NULL;
        TreeNode *root=Build(0,inorder.size()-1,0,postorder.size()-1,inorder,postorder);
        return root;
    }
    TreeNode *Build(int li,int ri,int lp,int rp,vector<int> &inorder , vector<int> &postorder){
        int i;
        if(li>ri)
            return NULL;
        TreeNode *left,*right;
        TreeNode *root=new TreeNode(postorder[rp]);
        for(i=li ; i<=ri ;i++)
            if(inorder[i]==postorder[rp])
                break;
        int ca=i-li;//left num of numbers
        int cb=ri-i;//right num of number
        left=Build(li,i-1,lp,lp+ca-1,inorder,postorder);
        right=Build(i+1,ri,lp+ca,rp-1,inorder,postorder);
        root->left=left;
        root->right=right;
        return root;
    }
};


你可能感兴趣的:([leetcode] Construct Binary Tree from Inorder and Postorder Traversal)