👨🏫 题目地址
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root)
{
if (root == null)
return true;
return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean dfs(TreeNode root, long min, long max)
{
if (root.val <= min || root.val >= max)//等于边界值也不行
return false;
if (root.left != null && !dfs(root.left, min, root.val))
return false;
if (root.right != null && !dfs(root.right, root.val, max))
return false;
return true;
}
}
👨🏫 官方题解