Skip to content

Commit d750a94

Browse files
committed
🚀 28-Jul-2020
1 parent 4e4ea5a commit d750a94

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
Given inorder and postorder traversal of a tree, construct the binary tree.
2+
3+
Note:
4+
You may assume that duplicates do not exist in the tree.
5+
6+
For example, given
7+
8+
inorder = [9,3,15,20,7]
9+
postorder = [9,15,7,20,3]
10+
Return the following binary tree:
11+
12+
3
13+
/ \
14+
9 20
15+
/ \
16+
15 7
17+
18+
19+
20+
21+
22+
23+
/**
24+
* Definition for a binary tree node.
25+
* struct TreeNode {
26+
* int val;
27+
* TreeNode *left;
28+
* TreeNode *right;
29+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
30+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
31+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
32+
* };
33+
*/
34+
class Solution {
35+
public:
36+
TreeNode *Tree(vector<int>& in, int x, int y,vector<int>& po,int a,int b){
37+
if(x > y || a > b)return nullptr;
38+
TreeNode *node = new TreeNode(po[b]);
39+
int SI = x;
40+
while(node->val != in[SI])SI++;
41+
node->left = Tree(in,x,SI-1,po,a,a+SI-x-1);
42+
node->right = Tree(in,SI+1,y,po,a+SI-x,b-1);
43+
return node;
44+
}
45+
TreeNode* buildTree(vector<int>& in, vector<int>& po){
46+
return Tree(in,0,in.size()-1,po,0,po.size()-1);
47+
}
48+
};

0 commit comments

Comments
 (0)