## Leetcode: Construct Binary Tree from Preorder and Inorder Traversal

2018年04月13日 ⁄ 综合 ⁄ 共 912字 ⁄ 字号 评论关闭

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:

You may assume that duplicates do not exist in the tree.

```TreeNode* build(vector<int> &preorder,int left1,int right1,vector<int> &inorder,int left2,int right2)
{
if(right1-left1 != right2-left2)return NULL;
if(right1>=preorder.size() || right2>=inorder.size())return NULL;

if(left1==right1 && left2==right2)
{
TreeNode* root = new TreeNode(preorder[left1]);
return root;
}else if(left1<right1 && left2<right2)
{
TreeNode* root = new TreeNode(preorder[left1]);
int i;
for(i = left2; i <= right2; i++)
if(inorder[i] == preorder[left1])break;
if(i>right2)return NULL;
root->left = build(preorder,left1+1,left1+i-left2,inorder,left2,i-1);
root->right = build(preorder,left1+i-left2+1,right1,inorder,i+1,right2);
return root;
}else
return NULL;
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
// Note: The Solution object is instantiated only once.
return build(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}```