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
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
unordered_map<int,int> mp;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = inorder.size();
if(n<=0 || preorder.size() != n) return NULL;
for(int i=0;i<n;++i) mp[inorder[i]] = i;
return dfs(preorder,inorder,0,n-1,0,n-1);
}
TreeNode *dfs(vector<int>&p,vector<int> &i, int pl,int pr,int il,int ir) {
//root value
if(pl > pr|| il > ir) return NULL;
#define Node TreeNode
Node *root = new Node(p[pl]);
// 中序: 左根右
int mid = mp[root->val];
int SIZE = mid - il;
root->left = dfs(p,i,pl+1,pl+ SIZE, il,mid - 1);
root->right = dfs(p,i,pl+SIZE+1,pr, mid + 1, ir);
return root;
}
};
|