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:
    void f(vector<int> &inorder,int s1, int e1,vector<int> & postorder,int s2, int e2, TreeNode *& root){
        if (s1 > e1){
            return;
        }
        if (!root){
            root = new TreeNode(postorder[e2]);
            int m = s1;
            for(;m <= e1;m++){
                if (inorder[m] == postorder[e2]){
                    break;
                }
            }
            f(inorder,s1,m-1,postorder,s2,s2 + m - s1 - 1,root->left);
            f(inorder,m+1,e1,postorder,e2 - 1 - e1 + (m + 1) ,e2 - 1,root->right);
        }
    }
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (!inorder.size()){
            return NULL;
        }
        TreeNode * root = NULL;
        f(inorder,0,inorder.size() -1,postorder,0,postorder.size() -1,root);
        return root;
    }
};

 

posted @ 2013-07-02 00:18  一只会思考的猪  阅读(150)  评论(0编辑  收藏  举报