[LeetCode]Validate Binary Search Tree

两种解法,第一个是利用了前序遍历递增的特点

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;
    }
}

 

posted @ 2015-12-04 09:42  Weizheng_Love_Coding  阅读(116)  评论(0)    收藏  举报