-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathBinaryTreeFromInorderandPostorder.cpp
More file actions
44 lines (43 loc) · 1.34 KB
/
BinaryTreeFromInorderandPostorder.cpp
File metadata and controls
44 lines (43 loc) · 1.34 KB
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
//Construct a binary tree from Inorder and Postorder : Leetcode - Problem 106
/**
* 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:
TreeNode* buildTree(vector<int>& in, vector<int>& post) {
unordered_map<int, int> pos;
int n = post.size();
for (int i = 0; i < n; i++) {
pos[in[i]] = i;
}
TreeNode* root = NULL;
for (int i = n - 1; i >= 0; i--) {
int num = post[i], p = pos[num];
//cout << num << ":" << p << endl;
TreeNode* tr = new TreeNode(num);
if (i == n - 1) {
root = tr;
continue;
}
TreeNode* node = root, *prev = NULL;
while (node) {
prev = node;
if (pos[node->val] > p) node = node->left;
else node = node->right;
}
node = tr;
if (pos[prev->val] > p) prev->left = tr;
else prev->right = tr;
}
return root;
}
};
// Created by :-Swapnil0803