forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstruct-binary-tree-from-preorder-and-inorder-traversal_2(AC).cpp
More file actions
52 lines (51 loc) · 1.38 KB
/
construct-binary-tree-from-preorder-and-inorder-traversal_2(AC).cpp
File metadata and controls
52 lines (51 loc) · 1.38 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
#include <unordered_map>
using namespace std;
/**
* 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 preorder : A list of integers that preorder traversal of a tree
*@param inorder : A list of integers that inorder traversal of a tree
*@return : Root of a tree
*/
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
int n = preorder.size();
if (n == 0) {
return NULL;
}
int i;
for (i = 0; i < n; ++i) {
inPos[inorder[i]] = i;
}
return construct(preorder, inorder, 0, n - 1, 0, n - 1);
}
private:
unordered_map<int, int> inPos;
TreeNode *construct(vector<int> &pre, vector<int> &in,
int pll, int prr, int ill, int irr) {
int rootVal = pre[pll];
TreeNode *r = new TreeNode(rootVal);
int i = inPos[rootVal];
int len;
if (i > ill) {
len = i - ill;
r->left = construct(pre, in, pll + 1, pll + len, ill, i - 1);
}
if (i < irr) {
len = irr - i;
r->right = construct(pre, in, prr - len + 1, prr, i + 1, irr);
}
return r;
}
};