leetcode oj java 98. Validate Binary Search Tree
来源:互联网 发布:51单片机 多任务 编辑:程序博客网 时间:2024/05/23 00:07
一、问题描述:
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.
Example 1:
2 / \ 1 3Binary tree
[2,1,3]
, return true.Example 2:
1 / \ 2 3Binary tree
[1,2,3]
, return false.二、解决思路:
二分搜索树的中序遍历应该是一个有序的数组,把树中序遍历判断数组是否有序
三、代码:
package T12;import java.util.ArrayList;import java.util.List;/** * @author 作者 : xcy * @version 创建时间:2016年12月30日 下午1:58:43 * 类说明 */public class t98 { public static void main(String[] args) { // TODO Auto-generated method stub TreeNode root = new TreeNode(10); TreeNode r1 = new TreeNode(6); TreeNode r2 = new TreeNode(14); TreeNode r3 = new TreeNode(4); TreeNode r4 = new TreeNode(8); TreeNode r5 = new TreeNode(12); TreeNode r6 = new TreeNode(16); root.left = r1; root.right = r2; r1.left = r3; r1.right = r4; r2.left = r5; r2.right = r6; System.out.println(isValidBST(root)); } public static boolean isValidBST(TreeNode root) { if (root == null || (root.left == null && root.right == null)) { return true; } List<Integer> list = new ArrayList<Integer>(); genList(root, list); for (int i = 0; i < list.size() - 1; i++) { if (list.get(i) > list.get(i + 1)) return false; } return true; } public static void genList(TreeNode root, List<Integer> list) { if (root == null) { return; } genList(root.left, list); list.add(root.val); genList(root.right, list); }}
0 0
- leetcode oj java 98. Validate Binary Search Tree
- 98. Validate Binary Search Tree-leetcode-java
- leetcode-java-98. Validate Binary Search Tree
- LeetCode OJ:Validate Binary Search Tree
- LeetCode OJ - Validate Binary Search Tree
- LeetCode OJ - Validate Binary Search Tree
- LeetCode OJ Validate Binary Search Tree
- [Leetcode] Validate Binary Search Tree (Java)
- Validate Binary Search Tree LeetCode Java
- leetcode [Validate Binary Search Tree] java
- [LeetCode][Java] Validate Binary Search Tree
- [leetcode]98. Validate Binary Search Tree@Java解题报告
- LeetCode 98. Validate Binary Search Tree
- [LeetCode]98.Validate Binary Search Tree
- [Leetcode] 98. Validate Binary Search Tree
- LeetCode --- 98. Validate Binary Search Tree
- [leetcode] 98.Validate Binary Search Tree
- [leetcode] 98.Validate Binary Search Tree
- Set CORS on Express API
- g2o在ubuntu16.04安装及初步使用
- 为何 IntelliJ IDEA 比 Eclipse 更好
- JAVA设计模式之单例模式
- 请教各位大神一个关于安卓开发里面的web服务器的问题 急~~~
- leetcode oj java 98. Validate Binary Search Tree
- app安装包上传
- 关于ajax传送数组对象后台接收的问题
- 我的Eclipse使用笔记
- 0148 Spring Framework 中启动 Redis 事务操作
- android中用GLSurfaceview和opengl es2.0显示图片,图片无法正常显示
- 关于旅游方面是做手机App好还是微信公众平台好呢?
- sqlmap注入用法
- 关于mysql主从复制