https://leetcode.com/problems/validate-binary-search-tree/
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.
这道题要注意的是,不能只看每个节点的左右节点是否符合要求,而是要看每个节点的左子树都小于啊这个节点的值,每个节点的右子树都大于这个节点的值。
有两种方法,一是递归检查,并且传递给每个节点它不能超过的最大值和最小值,注意,如果一开始min, max被初始化为Integer.MIN_VALUE, Integer.MAX_VALUE的话,那么很可能一开始如果root的值就是MIN_VALUE或者MAX_VALUE的话就会直接返回false了,但其实这种情况是true。所以一开始min, max要初始化为long,并且别int所能表示的范围大,见代码:
public class Solution {
public boolean isValidBST(TreeNode root) {
if(root==null) return true;
long min = (long)Integer.MIN_VALUE-1;
long max = (long)Integer.MAX_VALUE+1;
return helper(root, min, max);
}
public boolean helper(TreeNode node, long min, long max){
if(node == null) return true;
if(node.val<=min || node.val >= max) return false;
return helper(node.left, min, node.val) && helper(node.right, node.val, max);
}
}
另一种方法是,如果是BST,那么inorder traversal肯定是sorted且递增的,所以可以记录一个previous的值,然后每次更新比较。但也要注意,如果把previous初始话为MIN_VALUE,也会出现上面说的那种corner case的情况,这时候可以新增一个count变量,如果是第一次更新previous,那么可以不需要满足任何条件,如果不是,则需要满足BST的条件。上面那种算法也可以用这种count的方法来解决,只是这样就需要两个count,一个记录第一次更新最小值,一个记录第一次更新最大值,总之比较麻烦,没有直接用long来得方便。
public class Solution {
private int previous = Integer.MIN_VALUE;
private int count = 0;
public boolean isValidBST(TreeNode root){
if(root == null) return true;
if(!isValidBST(root.left)) return false;
if (count!=0 && root.val<= previous) return false;
previous = root.val;
count++;
if(!isValidBST(root.right)) return false;
return true;
}
}