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.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) 
    {
        return build(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
    }
    TreeNode *build(vector<int> &inorder,int inl,int inr, vector<int> &postorder,int pl,int pr)
    {
        if(inl>inr) return NULL;
        
        TreeNode *root=new TreeNode(postorder[pr]);
        int index=inl;
        while(inorder[index]!=postorder[pr]) index++;
        root->left=build(inorder,inl,index-1,postorder,pl,pl+index-inl-1);
        root->right=build(inorder,index+1,inr,postorder,pr-(inr-index),pr-1);
    }
};

 

posted @ 2014-05-30 01:22  erictanghu  阅读(95)  评论(0编辑  收藏  举报