Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
[分析] 这题较一年之前的版本多了些边界值的test case,看出leetcode在不断优化完善,赞!
对我来说,对边界条件的考虑是bug free的关键。基本思路,判断根节点是否满足条件,然后递归判断左右子节点是否满足条件。判断是否满足BST性质,可以从根节点下传节点的值域,root的初始值域是多少呢,(Integer.MIN_VALUE, Integer.MAX_VALUE)貌似是一个合理的选择,但如果root本身就是Integer.MIN_VALUE或者是Intger.MAX_VALUE呢? 因此还需要使用两个辅助flag,effLowBound, effUpBound分别表示值域的上下边界是否有效,对于root,上下边界均无效。
public class Solution {
public boolean isValidBST(TreeNode root) {
return check(root, Integer.MIN_VALUE, Integer.MAX_VALUE, false, false);
}
public boolean check(TreeNode curr, int low, int up,
boolean effLowBound, boolean effUpBound) {
if (curr == null) return true;
if ((effLowBound && curr.val <= low) || (effUpBound && curr.val >= up))
return false;
return check(curr.left, low, curr.val, effLowBound, true)
&& check(curr.right, curr.val, up, true, effUpBound);
}
}
分享到:
相关推荐
leetcode-tag-Tree
《leetcode-solutions》,刷算法题,需要有一定的英文阅读能力。。。
IDEA 插件,lettcode刷题,leetcode-editor7.4版本下载进行本地导入(直接将压缩包拖进IDEA即可)
Algorithm-LeetCode-Sol-Res.zip,干净,易懂的解决方案和资源,为leetcode在线判断算法问题。,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。
Algorithm-leetcode-spider.zip,leetcode公司,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。
leetcode-cli-plugins leetcode-cli 的第 3 方插件。 什么是 如何使用 如何使用 插件 名称 描述 增强的命令 按公司或标签过滤问题 list 不要在同一台计算机上使 Chrome 的会话过期 login 不要在同一台计算机上使 ...
在IDE中解决LeetCode问题,支持leetcode.com与leetcode-cn.com,满足基本的做题需求。 理论上支持: IntelliJ IDEA PhpStorm WebStorm PyCharm RubyMine AppCode CLion GoLand DataGrip Rider MPS Android Studio。
解题思路思路和LeetCode-python 503.下一个更大元素 II一致,只是这里求的是下标的距离,而不是数值倒序搜索,用到栈,栈里存储索引情况1:若栈为
作者: 负雪明烛个人博客: :
leetcode 答案解析 golang解答
leetcode-cheat 的发布 它是什么 ? 这是一个chrome 扩展,可以帮助您更高效地使用 leetcode。您可以从 重要: leetcode-cheat 现在只支持中文版。 也就是说不完全支持leetcode.com,但是你可以用leetcode-cn.com代替...
~/.vscode/extensions/leetcode.vscode-leetcode-0.17.0/node_modules/vsc-leetcode-cli/bin/leetcode /usr/local/bin/leetcode 修改模板 open ~/.vscode/extensions/leetcode.vscode-leetcode-0.17.0/node_modules/...
leetcode-editor,在ide中做leetcode练习,支持leetcode.com和leetcode-cn.com,以满足练习的基本需求。理论上支持:intellij idea phpstorm webstorm pycharm rubymine appcode clion goland datagrip rider mps ...
leetcode-helper-1.7.1
leetcode-tag-dynamic programming
leetcode卡LeetCode---二分搜索 该存储库包括二进制搜索探索卡中所有问题的解决方案。
然后进入到LeetCode-Spider目录中修改config.json,其中outputDir需要填写该工程的/docs/views文件夹路径 { "username": "aaa", "password": "bbb", "outputDir": "/Users/liuyao/Downloads/LeetCode-Blog-Test/docs...
leetcode-cli 注意:这个存储库是为了临时使用而分叉的。 注意:从 webbrowser 复制 cookie 并使用leetcode user -c可以临时修复不能。 一个享受 leetcode 的高效 cli 工具! 非常感谢 leetcode.com,一个非常棒的...
LeetCode-BinarySearch