forked from walkccc/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0105.cpp
More file actions
32 lines (27 loc) · 843 Bytes
/
0105.cpp
File metadata and controls
32 lines (27 loc) · 843 Bytes
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
/**
* 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:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return helper(0, 0, preorder.size(), preorder, inorder);
}
private:
TreeNode* helper(int i, int j, int n, vector<int>& preorder, vector<int>& inorder) {
if (n == 0) return NULL;
TreeNode* root = new TreeNode(preorder[i]);
if (n == 1) return root;
int k = j;
while (inorder[k] != root->val) k++;
int l = k - j;
root->left = helper(i + 1, j, l, preorder, inorder);
root->right = helper(i + l + 1, j + l + 1, n - l - 1, preorder, inorder);
return root;
}
};