2

#yyds干货盘点# LeetCode 热题 HOT 100:验证二叉搜索树

 1 year ago
source link: https://blog.51cto.com/u_13321676/5763709
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点# LeetCode 热题 HOT 100:验证二叉搜索树

精选 原创

灰太狼_cxh 2022-10-17 17:26:17 博主文章分类:leetcode ©著作权

文章标签 子树 二叉搜索树 子节点 文章分类 Java 编程语言 阅读数156

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

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

节点的左子树只包含 小于 当前节点的数。

节点的右子树只包含 大于 当前节点的数。

所有左子树和右子树自身必须也是二叉搜索树。

输入:root = [2,1,3]

输出:true

输入:root = [5,1,4,null,null,3,6]

输出:false

解释:根节点的值是 5 ,但是右子节点的值是 4 。

代码实现:

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);
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK