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.
Example 1:
2
/ \
1 3
Binary tree [2,1,3], return true.
Example 2:
1
/ \
2 3
Binary tree [1,2,3], return false.
这题注意不能局部的看每个节点和其左右子孩子的值比较,应该看每个节点和其左右子树的比较。
这里有两种思路,一种从上至下,一种从下至上。
先说从下至上。
主要是思路是,每次获取以某个节点为根时,子树上的值的最小最大值,返回一个数组,递归的做这个过程。
如果在过程中发现不合法的,直接返回null。每个节点在判断是,获取左右子树的最小最大值,然后做判断。具体代码如下:
public class Solution {
public boolean isValidBST(TreeNode root) {
if(root==null) return true;
int[] res = getMinMax(root);
return res==null?false:true;
}
public int[] getMinMax(TreeNode root){
int[] res = {root.val, root.val};
int[] left = null,right = null ;
if(root.left!=null){
if(root.val <= root.left.val){
return null;
}else{
left = getMinMax(root.left);
if(left==null) return null;
}
if(root.val <= left[1]) return null;
else res[0] = left[0];
}
if(root.right!=null){
if(root.val >= root.right.val){
return null;
}else{
right = getMinMax(root.right);
if(right==null) return null;
}
if(root.val >= right[0]) return null;
else res[1] = right[1];
}
return res;
}
}
然而还有一种从上到下的方法。
主要思路是,每次check一个节点是,会先指定该节点的取值范围,如果不在范围类就非法,返回false。
public boolean isValidBST(TreeNode root) {
return isValid(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
public boolean isValid(TreeNode root, int min, int max){
if(root==null) return true;
if(root.val > max || root.val < min) return false;
return isValid(root.left, min, root.val-1) && isValid(root.right, root.val+1, max);
}
但是这个有个缺点,就是在最边界的情况下,会跪。怎么改,先留坑。