给定二叉树,确定它是否是有效的二叉搜索树
原题:98 https://leetcode.com/problems/validate-binary-search-tree/
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public boolean isValidBST(TreeNode root) {
return isValidBST(root, null, null);
}
private boolean isValidBST(TreeNode root, Integer max, Integer min) {
if (root == null) return true;//空树正确
if (max != null && root.val >= max)
return false;
if (min != null && root.val <= min)
return false;
return isValidBST(root.left, root.val, min) //判断左子树,以左子树当中root,root当做最大值,因为左子树不能大于max值
&&
isValidBST(root.right, max, root.val);//判断右子树,以右子树当中root,root当做最小值,因为右子树不能小于min值
}
网友评论