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:
It is the reversed version of #105.
Code:
/**
* 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* buildTree(vector<int>& inorder, vector<int>& postorder) {
return build(0,postorder.size()-1, 0, inorder.size()-1, postorder, inorder);
}
TreeNode *build(int pos_s, int pos_e,int in_s, int in_e, vector<int>& postorder, vector<int>& inorder){
if(pos_s > pos_e || in_s > in_e) return NULL;
TreeNode *root = new TreeNode(postorder[pos_e]);
int pivot = -1;
for(int i = in_e; i >= in_s; i --){
if(inorder[i] == root->val){
pivot = i;
break;
}
}
int rightnum = in_e - pivot;
root->left = build(pos_s, pos_e - 1 - rightnum, in_s, pivot - 1, postorder, inorder);
root->right = build(pos_e - rightnum, pos_e-1, pivot + 1, in_e, postorder, inorder);
return root;
}
};