LeetCode-热题100-笔记-day28

98. 验证二叉搜索树icon-default.png?t=N7T8https://leetcode.cn/problems/validate-binary-search-tree/

给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。

有效 二叉搜索树定义如下:

  • 节点的左子树只包含 小于 当前节点的数。
  • 节点的右子树只包含 大于 当前节点的数。
  • 所有左子树和右子树自身必须也是二叉搜索树。

示例 1:

LeetCode-热题100-笔记-day28_第1张图片

输入:root = [2,1,3]
输出:true
class Solution {
    public boolean isValidBST(TreeNode root) {
        return bfs(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    public boolean bfs(TreeNode node, long lower, long upper){
        if(node==null){
            return true;
        }
        if(node.val<=lower||node.val>=upper){
            return false;
        }
        return bfs(node.left, lower, node.val)&&bfs(node.right, node.val, upper);
    }
}

 

你可能感兴趣的:(leetcode,leetcode,笔记,算法)