106 Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
- Note: You may assume that duplicates do not exist in the 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>& inorder, int is, int ie, vector<int>& postorder, int ps, int pe) {
if ( is > ie ) return NULL;
int i;
for ( i = is; i <= ie-1; i++ ) if ( inorder[i] == postorder[pe] ) break;
TreeNode* ptree = new TreeNode(postorder[pe]);
ptree->left = help(inorder, is, i-1, postorder, ps, ps-is+i-1);
ptree->right = help(inorder, i+1, ie, postorder, ps-is+i, pe-1);
return ptree;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return help(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);
}
};
Notes
Use sub-vector constructor may encounter "exceed memory limit" problem.