标签:
两种解法,第一个是利用了前序遍历递增的特点
public class Solution { long count = Long.MIN_VALUE; public boolean isValidBST(TreeNode root) { if (root == null) { return true; } if (root.left != null) { if (!isValidBST(root.left)) { return false; } } if (root.val <= count) { return false; } count = root.val; if (root.right != null) { if (!isValidBST(root.right)) { return false; } } return true; } }
public class Solution { public boolean isValidBST(TreeNode root) { if (root == null) { return true; } return helper(root, Long.MAX_VALUE, Long.MIN_VALUE); } public boolean helper(TreeNode root, long max, long min) { if (root.val >= max || root.val <= min) { return false; } if (root.left != null) { if (!helper(root.left, (long)root.val, min)) { return false; } } if (root.right != null) { if (!helper(root.right, max, (long)root.val)) { return false; } } return true; } }
[LeetCode]Validate Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/vision-love-programming/p/5018388.html