思路:逐层传值,在下一层节点进行比较,如果不符合返回假,同时如果遍历到根部了,即为空,则返回true
var isValidBST = function(root) {
const helper=(root,lower,upper)=>{
if(!root) return true;
//划定一个区间,当前节点大于左边小于右边,不符合则为假
if(root.val <= lower || root.val >= upper) return false;
//
return helper(root.left, lower, root.val) && helper(root.right, root.val, upper);
}
return helper(root,-Infinity, Infinity);
}
验证二叉搜索树
最新推荐文章于 2024-07-15 17:15:24 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)