-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvert Sorted Array to Binary Search Tree.cpp
More file actions
73 lines (62 loc) · 1.99 KB
/
Convert Sorted Array to Binary Search Tree.cpp
File metadata and controls
73 lines (62 loc) · 1.99 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// recursion
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num) {
return build(num, 0, num.size() - 1);
}
TreeNode *build(vector<int> &num, int l, int h) {
if (l > h) return NULL;
if (l == h) {
TreeNode *node = new TreeNode(num[l]);
return node;
}
int mid = (l + h) / 2;
TreeNode *root = new TreeNode(num[mid]);
root->left = build(num, l, mid - 1);
root->right = build(num, mid + 1, h);
return root;
}
};
// iteration, 纯粹作死
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num) {
if (num.size() == 0) return NULL;
stack<pair<TreeNode *, pair<int, int>>> s;
TreeNode *root = new TreeNode(num[(num.size() - 1) / 2]);
pair<int, int> pr(0, num.size() - 1);
pair<TreeNode *, pair<int, int>> ps(root, pr);
s.push(ps);
while (!s.empty()) {
pair<TreeNode *, pair<int, int>> p = s.top();
s.pop();
int l = p.second.first;
int h = p.second.second;
int m = (l + h) / 2;
if (m+1 <= h) {
TreeNode *rnode = new TreeNode(num[(m+h+1)/2]);
p.first->right = rnode;
pair<int, int> rpr(m+1, h);
pair<TreeNode *, pair<int, int>> rps(rnode, rpr);
s.push(rps);
}
if (l <= m-1) {
TreeNode *lnode = new TreeNode(num[(l+m-1)/2]);
p.first->left = lnode;
pair<int, int> lpr(l, m-1);
pair<TreeNode *, pair<int, int>> lps(lnode, lpr);
s.push(lps);
}
}
return root;
}
};