Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
35 lines (29 sloc) 1.06 KB
problem:
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:
///////////////////////
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode *buildTree_aux(vector<int> &inorder, int inBegin, int inEnd, vector<int> &postorder, int postBegin, int postEnd)
{
if(inEnd - inBegin != postEnd - postBegin || inBegin > inEnd)
return NULL;
TreeNode *root = new TreeNode(postorder[postEnd]);
int i = inBegin;
while(i <= inEnd && inorder[i] != postorder[postEnd])
i++;
root->left = buildTree_aux(inorder, inBegin, i - 1, postorder, postBegin, postBegin + i - inBegin - 1);
root->right = buildTree_aux(inorder, i + 1, inEnd, postorder, postBegin + i - inBegin, postEnd -1);
return root;
}
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
{
return buildTree_aux(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
}