LeetCode-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* Build(vector<int>& inorder,vector<int>& preorder,int s1,int e1,int s2,int e2){
        if(s1>e1||s2>e2)return NULL;
        TreeNode* ret=new TreeNode(preorder[s2]);
        int i=s1;
        while(i<=e1){
            if(inorder[i]==preorder[s2])break;
            i++;
        }
        ret->left=Build(inorder,preorder,s1,i-1,s2+1,s2+i-s1);
        ret->right=Build(inorder,preorder,i+1,e1,s2+i-s1+1,e2);
    }
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        return Build(inorder,preorder,0,inorder.size()-1,0,inorder.size()-1);
    }
};
View Code

 

posted @ 2013-10-03 22:54  懒猫欣  阅读(153)  评论(0编辑  收藏  举报