Skip to content

Commit bdde47b

Browse files
committed
Create Construct Binary Tree from Inorder and Postorder Traversal.cpp
1 parent 7257b79 commit bdde47b

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Definition for binary tree
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
TreeNode *buildTree(vector<int> &postorder, vector<int> &inorder,int l1,int r1,int l2,int r2) {
13+
// Start typing your C/C++ solution below
14+
// DO NOT write int main() function
15+
if (l1>r1||l2>r2||r1>=postorder.size()||r2>=inorder.size())return NULL;
16+
TreeNode *p=new TreeNode(postorder[r1]);
17+
int i;
18+
for (i=l2;i<=r2;i++)
19+
{
20+
if (inorder[i]==postorder[r1])break;
21+
}
22+
p->left=buildTree(postorder,inorder,l1,l1+i-l2-1,l2,i-1);
23+
p->right=buildTree(postorder,inorder,l1+i-l2,r1-1,i+1,r2);
24+
return p;
25+
}
26+
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
27+
// Start typing your C/C++ solution below
28+
// DO NOT write int main() function
29+
if (inorder.empty())return NULL;
30+
return buildTree(postorder,inorder,0,postorder.size()-1,0,inorder.size()-1);
31+
}
32+
};

0 commit comments

Comments
 (0)