力扣 验证二叉搜索树 递归

‍ 题目地址

力扣 验证二叉搜索树 递归_第1张图片

/**
 * 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;
	}
}

‍ 官方题解

你可能感兴趣的:(力扣,hot100,leetcode,算法,职场和发展)