-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path1008.cpp
More file actions
58 lines (54 loc) · 1.61 KB
/
1008.cpp
File metadata and controls
58 lines (54 loc) · 1.61 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
53
54
55
56
57
58
/**
* 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:
vector<int> pre;
TreeNode* bstFromPreorder(vector<int>& preorder) {
if (preorder.size() == 0) return nullptr;
pre = preorder;
return buildTree(0, preorder.size()-1);
}
TreeNode* buildTree(int start, int end) {
if (start > end) return nullptr;
TreeNode* root = new TreeNode(pre[start]);
int mid = findNextLarge(start+1, end, pre[start]);
root->left = buildTree(start+1, mid-1);
root->right = buildTree(mid, end);
return root;
}
int findNextLarge(int start, int end, int target) {
for (int i = start; i <= end; ++i) {
if (target < pre[i]) {
return i;
}
}
return end+1;
}
};
class Solution {
public:
vector<int> pre;
int id;
TreeNode* bstFromPreorder(vector<int>& preorder) {
if (preorder.size() == 0) return nullptr;
pre = preorder;
id = 0;
return buildTree(100000);
}
TreeNode* buildTree(int bound) {
if (id >= pre.size() || pre[id] > bound) return nullptr;
TreeNode* root = new TreeNode(pre[id++]);
root->left = buildTree(root->val);
root->right = buildTree(bound);
return root;
}
};