From : https://leetcode.com/problems/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 a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTreeRecursive(vector<int>& pre, vector<int>& in, int s1, int e1, int s2, int e2) {
if(s1>e1) return NULL;
if(s1==e1) return new TreeNode(pre[s1]);
TreeNode* root = new TreeNode(pre[s1]);
int index=s2, rootV=root->val;
while(rootV != in[index]) index++;
root->left = buildTreeRecursive(pre, in, s1+1, s1+index-s2, s2, index-1);
root->right = buildTreeRecursive(pre, in, s1+index-s2+1, e1, index+1, e2);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.size()==0 || inorder.size()==0) return NULL;
int start = 0, end = preorder.size()-1;
return buildTreeRecursive(preorder, inorder, start, end, start, end);
}
};