首页 > 其他 > 详细

[LeetCode]Validate Binary Search Tree

时间:2015-12-04 10:49:15      阅读:309      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!