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.

/**
 * 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> &preorder, vector<int> &inorder) 
    {
        return buildTree(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
    }
    TreeNode *buildTree(const vector<int> &preorder,int pl,int pr,const vector<int> &inorder,int il,int ir)
    {
        if(pl>pr) return NULL;
        TreeNode* root=new TreeNode(preorder[pl]);
        int mid=il;
        while(inorder[mid]!=root->val) mid++;
        root->left=buildTree(preorder,pl+1,pl+mid-il,inorder,il,mid-1);
        root->right=buildTree(preorder,pr+1-(ir-mid),pr,inorder,mid+1,ir);
    }
};

 

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