public static boolean isValidBST(TreeNode root) { if(root==null) return true; return dfs(root, -Double.MAX_VALUE, Double.MAX_VALUE); // 注意Double.MIN_VALUE是接近0的正数 } public static boolean dfs(TreeNode root, double min_bound, double max_bound){ //设置两个参数,一个最大值,一个最小值 if (root == null) return true; if (root.val >= max_bound || root.val <= min_bound) return false; return dfs(root.left, min_bound, root.val) && dfs(root.right, root.val, max_bound); }
官方
class Solution { public boolean isValidBST(TreeNode root) { return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE); } public boolean isValidBST(TreeNode node, long lower, long upper) { if (node == null) { return true; } if (node.val <= lower || node.val >= upper) { return false; } return isValidBST(node.left, lower, node.val) && isValidBST(node.right, node.val, upper); } }