-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path1008.cpp
More file actions
24 lines (23 loc) · 711 Bytes
/
Copy path1008.cpp
File metadata and controls
24 lines (23 loc) · 711 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
class Solution {
public:
TreeNode *bstFromPreorder(vector<int> &preorder) {
return Construct(preorder, 0, preorder.size());
}
TreeNode *Construct(vector<int> &preorder, int begin, int end) {
if (begin >= end)
return nullptr;
auto node = new TreeNode(preorder[begin]);
int i = begin + 1, j = end, mid = 0;
while (i < j) {
mid = i + (j - i) / 2;
if (preorder[mid] < preorder[begin])
i = mid + 1;
else
j = mid;
}
j = max(i, j);
node->left = Construct(preorder, begin + 1, j);
node->right = Construct(preorder, j, end);
return node;
}
};