Validate Binary Search Tree
来源:互联网 发布:小米开源软件 编辑:程序博客网 时间:2024/06/06 17:41
1.题目
给定一个二叉树,判断它是否是合法的二叉查找树(BST)
一棵BST定义为:
- 节点的左子树中的值要严格小于该节点的值。
- 节点的右子树中的值要严格大于该节点的值。
- 左右子树也必须是二叉查找树。
- 一个节点的树也是二叉查找树。
样例
一个例子:
2 / \1 4 / \ 3 5
上述这棵二叉树序列化为 {2,1,4,#,#,3,5}
.
2.算法
由于二叉查找树的中序遍历是递增的,我们可以利用这条性质检验
public boolean isValidBST(TreeNode root) { // write your code here ArrayList<Integer> list = new ArrayList<Integer>(); list.add(null); return helper(root, list); } public boolean helper(TreeNode root, ArrayList<Integer> list) { if (root == null) { return true; } boolean left = helper(root.left, list); if (list.get(0) != null && list.get(0) >= root.val) { return false; } list.set(0, root.val); return left && helper(root.right, list); }
0 0
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- web标准—可用性、可维护性、可访问性
- 推送
- 自定义侧滑框
- 个人记录-LeetCode 66. Plus One
- JavaScript之js对象终极序列化(可序列化函数)
- Validate Binary Search Tree
- 日常积累180104
- MQTT
- mybatis源码学习之执行过程分析(5)——sql执行后ResultSet的处理及结果返回
- 程序实训—电子词典
- poj3020Antenna Placement
- alsa 添加codec
- 清除浮动的几种常用方法
- mosquitto