-
Notifications
You must be signed in to change notification settings - Fork 0
/
Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.txt
41 lines (37 loc) · 1.37 KB
/
Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *buildTreeHelper(vector<int> &inorder,int li, int ri,vector<int> &postorder, int lp, int rp){
if (li>ri || lp>rp) return NULL;
int rootvalue = postorder[rp];
TreeNode *node = new TreeNode(rootvalue);
int leftsize, rightsize;
for (int i=li; i<=ri; ++i){
if (rootvalue==inorder[i]){
leftsize = i-li;
rightsize = ri-i;
break;
}
}
node->left = buildTreeHelper(inorder,li,li+leftsize-1,postorder,lp,lp+leftsize-1);
node->right = buildTreeHelper(inorder,ri-rightsize+1,ri,postorder,rp-rightsize,rp-1);
return node;
}
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return buildTreeHelper(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
}
};
1.IDEA and Note please refer to the file: "Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.txt"