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) {
		return dfs(root, null, null);
	}

	static boolean dfs(TreeNode root, TreeNode lower, TreeNode upper) {
		if (root == null) return true; // 检查到头返回有效
        // 检查当前节点是否在允许的范围内
        if (lower != null && root.val <= lower.val) return false;
        if (upper != null && root.val >= upper.val) return false;
        // upper传入当前节点,因为左节点都要小于当前节点
        // lower传入当前节点,因为右节点都要大于当前节点
        return dfs(root.left, lower, root) && dfs(root.right, root, upper);
	}
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐