0%

1008. Construct Binary Search Tree from Preorder Traversal

O(n) time O(h) space
单调递减栈,因为对于每一个数x,都要找从左开始第一个比它小的数y,x是y的右子

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
/**
* 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* bstFromPreorder(vector<int>& preorder) {
TreeNode dummy_root(INT_MAX);
stack<TreeNode *> s({&dummy_root});
for (int x : preorder) {
auto n = new TreeNode(x);
TreeNode *p = nullptr;
while (s.top()->val < x) {
p = s.top();
s.pop();
}
if (p) {
p->right = n;
} else {
s.top()->left = n;
}
s.push(n);
}
return dummy_root.left;
}
};

recursive O(n) time O(h) space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 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:
int i = 0;
TreeNode* bstFromPreorder(vector<int>& A, int bound = INT_MAX) { // bound是当前返回的这棵树的最大值上限
if (i == A.size() || A[i] >= bound) return nullptr; // 当处理到叶结点的子结点时A[i] > bound
TreeNode* root = new TreeNode(A[i++]);
root->left = bstFromPreorder(A, root->val);
root->right = bstFromPreorder(A, bound);
return root;
}
};