Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
啊啊啊啊啊這道題最賤的地方在於!!!你要考慮這種情況:
4 雖然放在2的後面是對的,但是4比root借點3要大啊!也就是說4本來是應該放到右邊的subtree上去的,結果放到了左邊,也就是說違反了BST重要的原則之一:left subtree的所有節點都小於根節點,right subtree的所有節點都大於root節點。
也就是說任意一個節點應該 > 左上的結點,但是又小於左上的結點繼承過來的root。也就是說,比如說對4來說,4需要 2 < 4 < 3。
所以這個recursive,通過遞歸來更新每一個節點的min和max的判斷。
public boolean isValidBST(TreeNode root){
return helper(root,null,null);
}
public static boolean helper(TreeNode root, Integer min, Integer max){
if(root==null) return true;
if(max!=null && root.val >= max) return false;
if(min!=null && root.val <= min) return false;
return helper(root.left,min,root.val) && helper(root.right, root.val, max);
}
順便再附上一個好理解的,不過效率低,通不過leetcode。
就是每一個root要大於左子樹的最大值,root要小於右子樹的最小值:
//below is simple method but not efficient
public boolean isBST(TreeNode root){
if(root == null)
return true;
if(root.left!=null && root.left.val > max(root.left))
return false;
if(root.right!=null && root.right.val < min(root.right))
return false;
return isBST(root.left) && isBST(root.right);
}
private int max(TreeNode root){
int max = root.val;
while(root.right!=null){
max = root.right.val;
}
return max;
}
private int min(TreeNode root){
int min = root.val;
while(root.left!=null){
min = root.left.val;
}
return min;
}