leetcode--ValidateBinarySearchTree
2015-06-17 20:26
302 查看
思路:在递归参数中加入左区间和右区间,当递归左子节点时更新右区间,当递归右子节点时更新左区间。
可以简单地证明一下,如果左子节点要符合BST要求,首先得符合当前节点的区间范围,然后要小于当前节点。因此更新右区间。
/**
* Created by marsares on 15/6/17.
*/
public class ValidateBinarySearchTree {
boolean isValidBST=true;
public boolean isValidBST(TreeNode root) {
if(root==null)return true;
traversal(root,Long.MIN_VALUE,Long.MAX_VALUE);
return isValidBST;
}
public void traversal(TreeNode root,long left,long right){
if(root==null)return;
if(!isValidBST)return;
if(root.val<=left||root.val>=right)isValidBST=false;
traversal(root.left,left,root.val);
traversal(root.right,root.val,right);
}
public static void main(String[]args){
ValidateBinarySearchTree vbst=new ValidateBinarySearchTree();
BinaryTreeSerialize bts=new BinaryTreeSerialize();
TreeNode root=bts.Unserialize("{1,1}");
System.out.println(vbst.isValidBST(root));
}
}
可以简单地证明一下,如果左子节点要符合BST要求,首先得符合当前节点的区间范围,然后要小于当前节点。因此更新右区间。
/**
* Created by marsares on 15/6/17.
*/
public class ValidateBinarySearchTree {
boolean isValidBST=true;
public boolean isValidBST(TreeNode root) {
if(root==null)return true;
traversal(root,Long.MIN_VALUE,Long.MAX_VALUE);
return isValidBST;
}
public void traversal(TreeNode root,long left,long right){
if(root==null)return;
if(!isValidBST)return;
if(root.val<=left||root.val>=right)isValidBST=false;
traversal(root.left,left,root.val);
traversal(root.right,root.val,right);
}
public static void main(String[]args){
ValidateBinarySearchTree vbst=new ValidateBinarySearchTree();
BinaryTreeSerialize bts=new BinaryTreeSerialize();
TreeNode root=bts.Unserialize("{1,1}");
System.out.println(vbst.isValidBST(root));
}
}
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解
- LeetCode 2: Add Two Numbers (JAVA)
- LeetCode 1: Two Sum (JAVA)