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) {

if(preorder.size()==0|| inorder.size()==0)
return NULL;
return solve(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}

TreeNode *solve(vector<int> &preorder,int s1,int e1,vector<int> &inorder,int s2,int e2)
{
int rootVal=preorder[s1];
int rootIndex=-1;
for(int i=s2;i<=e2;i++)
if(inorder[i]==rootVal)
{
rootIndex=i;
break;
}
int left=rootIndex-s2;
int right=e2-rootIndex;
TreeNode *rootNode=new TreeNode(rootVal);
if(left>0)
rootNode->left=solve(preorder,s1+1,s1+left,inorder,s2,rootIndex-1);
if(right>0)
rootNode->right=solve(preorder,s1+left+1,e1,inorder,rootIndex+1,e2);

return rootNode;
}
};