105 Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.
Solution
/**
* 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* help(vector<int>& preorder, int ps, int pe, vector<int>& inorder, int is, int ie) {
if ( ps > pe ) return NULL;
int i;
for ( i = is; i <= ie; i++ ) if ( inorder[i] == preorder[ps] ) break;
TreeNode *ptree = new TreeNode(preorder[ps]);
ptree->left = help(preorder, ps+1, ps+i-is, inorder, is, i-1);
ptree->right = help(preorder, ps+i-is+1, pe, inorder, i+1, ie);
return ptree;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return help(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
}
};