一、Problem
Return the root node of a binary search tree that matches the given preorder traversal.
Constraints:
1 <= preorder.length <= 100
1 <= preorder[i] <= 10^8
The values of preorder are distinct.
二、Solution
方法一:遞歸
思路
根據 BST 性質可得,a[0] 就是 BST 的根,從左往右數第一個大於 a[0] 的值就是右子樹的開端,可基於這一點遞歸構造左右子樹
class Solution {
TreeNode dfs(int l, int r, int[] a) {
if (l > r)
return null;
TreeNode root = new TreeNode(a[l]);
int rStart = l;
while (rStart <= r && a[rStart] <= a[l])
rStart++;
root.left = dfs(l+1, rStart-1, a);
root.right = dfs(rStart, r, a);
return root;
}
public TreeNode bstFromPreorder(int[] preorder) {
return dfs(0, preorder.length-1, preorder);
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,