forked from sureshmangs/Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path106. Construct Binary Tree from Inorder and Postorder Traversal.cpp
73 lines (45 loc) · 1.5 KB
/
106. Construct Binary Tree from Inorder and Postorder Traversal.cpp
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
/**
* 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* constructTree(vector<int> &postorder, vector<int> &inorder, int start, int end){
static int pIndex=end;
if(start>end) return NULL;
TreeNode* tNode= new TreeNode(postorder[pIndex--]);
if(start==end) return tNode;
int index=mp[tNode->val];
tNode->right=constructTree(postorder, inorder, index+1, end);
tNode->left=constructTree(postorder, inorder, start, index-1);
return tNode;
}
TreeNode* buildTree(vector<int> &inorder, vector<int>& postorder) {
int n=inorder.size();
// Storing data in map for O(1) searching
for(int i=0;i<n;i++)
mp[inorder[i]]=i;
return constructTree(postorder, inorder, 0, n-1); // <postorder, inorder, start, end>
}
};
// Code gives Heap buffer overflow error