Validate Binary Search Tree
2015-06-07 12:41
405 查看
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.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isValidBST(TreeNode root) { if (root == null) return true; return isSubtreeLessThan(root.left, root.val) && isSubtreeGreaterThan(root.right, root.val) && isValidBST(root.left) && isValidBST(root.right); } private boolean isSubtreeLessThan(TreeNode root, int value) { if (root == null) return true; return root.val < value && isSubtreeLessThan(root.left, value) && isSubtreeLessThan(root.right, value); } private boolean isSubtreeGreaterThan(TreeNode root, int value) { if (root == null) return true; return root.val > value && isSubtreeGreaterThan(root.left, value) && isSubtreeGreaterThan(root.right, value); } }
相关文章推荐
- 设计模式之十三:适配器模式(Adapter)
- BZOJ 1646: [Usaco2007 Open]Catch That Cow 抓住那只牛( BFS )
- 使用JQuery实现全选的功能
- URL重写的几种实现方式的总结
- [c++]String字符串类的运算符重载
- apache+tomcat二级域名+url重写
- 运营开源公司的三个经验教训
- 让vs2008与vs2012同时打开同一个项目文件
- Apaceh配置虚拟主机步骤
- 单链表操作
- QLabel实现超链接,设置超链接颜色,去掉超链接下划线方法
- 最近学习的总结
- python并行计算的简单实现--pp
- 单链表操作 分类: 链表 2015-06-07 12:38 14人阅读 评论(0) 收藏
- 自定义拖拽框插件
- honeyd蜜罐配置和web监听脚本
- 用vs2008打开vs2012项目
- 深入理解C++中public、protected及private用法
- 仿flash运动框架
- nginx和Tomcat集成后发生的重定向问题分析和解决