Leetcode 98. Validate Binary Search Tree
2016-01-27 01:13
429 查看
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
read more on how binary tree is serialized on OJ.
Analysis:就是一个LinkedList, 然后进行中序遍历,得到的List再从前往后进行遍历,判断是否是递减的顺序
因为判断时候满足Binary Search Tree 的标准和中序遍历得到的结果相同
/**
* 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) {
List<Integer> res = new LinkedList<Integer>();
if(root == null)
return true;
helper(root,res);
Iterator iterator = res.iterator();
int position = 0;
int last = 0;
while(iterator.hasNext()){
int tem = (Integer)iterator.next();
position ++;
if(position == 1){
last = tem;
continue;
}
if(tem <= last)
return false;
}
return true;
}
public void helper(TreeNode tem,List<Integer> result ){
if(tem == null)
return;
helper(tem.left,result);
result.add(tem.val);
helper(tem.right,result);
}
}
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.
Analysis:就是一个LinkedList, 然后进行中序遍历,得到的List再从前往后进行遍历,判断是否是递减的顺序
因为判断时候满足Binary Search Tree 的标准和中序遍历得到的结果相同
/**
* 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) {
List<Integer> res = new LinkedList<Integer>();
if(root == null)
return true;
helper(root,res);
Iterator iterator = res.iterator();
int position = 0;
int last = 0;
while(iterator.hasNext()){
int tem = (Integer)iterator.next();
position ++;
if(position == 1){
last = tem;
continue;
}
if(tem <= last)
return false;
}
return true;
}
public void helper(TreeNode tem,List<Integer> result ){
if(tem == null)
return;
helper(tem.left,result);
result.add(tem.val);
helper(tem.right,result);
}
}
相关文章推荐
- Js年龄计算,精确到岁、月、小时
- [置顶] MarkDown使用
- java splite分割
- Fiddler拦截http请求修改数据
- iOS之地理位置及定位系统 -- 入门笔记(用Swift)
- [算法]位运算问题之一
- Leetcode 101. Symmetric Tree
- FFMpeg压缩Android摄像头数据写成H264格式文件
- 利用Fiddler对Android模拟器网络请求进行抓包
- 灰盒测试技术
- RESTful
- hdu 3
- xCode - 静态库
- 第一章 游戏开发环境-项目工具的选择
- Longest k-Good Segment
- hdu
- HDU3966(树链剖分) 模板题
- [ 备忘 ] php 正则表达式与 mysql IN 查询的排序问题
- [傅里叶变换及其应用学习笔记] 二十七. 高维傅里叶变换,复习
- fiddler抓包