題目
Return the root node of a binary search tree that matches the given preorder
traversal.
(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left
has a value <
node.val
, and any descendant of node.right
has a value >
node.val
. Also recall that a preorder traversal displays the value of the node
first, then traverses node.left
, then traverses node.right
.)
Example 1:
Input: [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]
Note:
1 <= preorder.length <= 100
- The values of
preorder
are distinct.
解答
這道題是說給一個前序遍歷的數組,根據它來構造一個BST。
這道題一開始想了個解法,但是錯了,後來參考了一下別人的解答。BST的特性是,左子樹的所有節點都小於根節點。右子樹的所有節點都大於根節點。
想象一下3個數的情況,第一個數肯定會被構造出來作爲根節點,那麼第二個數,可能大於,也可能小於根節點。也就是說,必須要知道,當前這個根節點的左子樹有個邊界,剩下的數都必須小於當前節點,才能成爲我的左子樹。
那麼算法過程大致上如下:
1.取第index個數構造一個root節點。
2.構造root的left,必須小於root.val才行,否則構造一個null
2.構造root的right,必須小於Integer.MAX才行,否則構造一個null
static int i = 0;
public TreeNode bstFromPreorder(int[] preorder) {
i = 0;
return build(preorder, Integer.MAX_VALUE);
}
public static TreeNode build(int[] preorder, int bound) {
if (i == preorder.length || preorder[i] > bound) return null;
TreeNode root = new TreeNode(preorder[i++]);
root.left = build(preorder, root.val);
root.right = build(preorder, bound);
return root;
}