forked from Nanduag0/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathConstructBinaryTreeFromInorder&PostOrder.txt
41 lines (38 loc) · 1.23 KB
/
ConstructBinaryTreeFromInorder&PostOrder.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
unordered_map<int,int> mp;
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder)
{
if(inorder.size()==0 || postorder.size()==0)
return NULL;
for(int i=0;i<inorder.size();i++)
{
mp[inorder[i]]=i;
}
return solve(inorder,postorder,0,inorder.size(),0,inorder.size());
}
// postorder-- left right root
// preorder-- root left right
TreeNode* solve(vector<int> inorder,vector<int> postorder,int i1,int i2,int j1,int j2)
{
if(i1>=i2 || j1>=j2)
return NULL;
TreeNode* temp=new TreeNode(postorder[j2-1]);
int indx=mp[temp->val];
int diff=indx-i1;
temp->left=solve(inorder,postorder,i1,i1+diff,j1,j1+diff);
temp->right=solve(inorder,postorder,i1+diff+1,i2,j1+diff,j2-1);
return temp;
}
};