forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstruct-binary-tree-from-inorder-and-postorder-traversal_2(AC).cpp
More file actions
52 lines (51 loc) · 1.4 KB
/
construct-binary-tree-from-inorder-and-postorder-traversal_2(AC).cpp
File metadata and controls
52 lines (51 loc) · 1.4 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
45
46
47
48
49
50
51
52
// Make it faster with hashing.
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
*@param inorder : A list of integers that inorder traversal of a tree
*@param postorder : A list of integers that postorder traversal of a tree
*@return : Root of a tree
*/
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
inPos.clear();
int n = inorder.size();
if (n == 0) {
return NULL;
}
int i;
for (i = 0; i < n; ++i) {
inPos[inorder[i]] = i;
}
return construct(inorder, postorder, 0, n - 1, 0, n - 1);
}
private:
unordered_map<int, int> inPos;
TreeNode *construct(vector<int> &in, vector<int> &post,
int ill, int irr, int pll, int prr) {
int rootVal = post[prr];
TreeNode *r = new TreeNode(rootVal);
int i = inPos[rootVal];
int len;
if (i > ill) {
len = i - ill;
r->left = construct(in, post, ill, i - 1, pll, pll + len - 1);
}
if (i < irr) {
len = irr - i;
r->right = construct(in, post, i + 1, irr, prr - len, prr - 1);
}
return r;
}
};