LeetCode刷题笔录 Validate Binary Search Tree

50 篇文章 0 订阅
15 篇文章 0 订阅

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.
上来先Brute force吧,没啥好说的。检查每个node的左子树的所有node都小于这个node,右子树的所有node都大于这个node。
public class Solution {
    public boolean isValidBST(TreeNode root) {
        if(root == null){
            return true;
        }
        return isSubTreeLessThan(root.left, root.val) && isSubTreeGreaterThan(root.right, root.val) && isValidBST(root.left) && isValidBST(root.right);
    }
    
    public boolean isSubTreeLessThan(TreeNode node, int val){
        if(node == null){
            return true;
        }
        return node.val < val && isSubTreeLessThan(node.left, val) && isSubTreeLessThan(node.right, val);
    }
    
    public boolean isSubTreeGreaterThan(TreeNode node, int val){
        if(node == null){
            return true;
        }
        return node.val > val && isSubTreeGreaterThan(node.left, val) && isSubTreeGreaterThan(node.right, val);
    }
    
    
}

改进一下。想到了AI课上学的alpha-beta pruning。一棵树的根为a,右子树为b,那么右子树的左儿子c的值一定是大于a且小于b。这样coding就好办了
public class Solution {
    public boolean isValidBST(TreeNode root) {
        return isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
        
    }
    
    public boolean isBST(TreeNode node, int alpha, int beta){
        if(node == null){
            return true;
        }
        if(alpha < node.val && node.val < beta){
            return isBST(node.left, alpha, node.val) && isBST(node.right, node.val, beta);
        }
        else
            return false;
    }
    
    
}

还有一种方法:如果一棵树是BST,那么如果做一个in order traversal的话产生的数组应该是排好序的。这样就一边进行in order traversal,一边比较当前值是不是比前一个值大就行了。这里用了个static变量来记录之前的值,使其在递归时能被记住。如果用C++的话按引用传递就不需要static了。
public class Solution {
    public static int previous = Integer.MIN_VALUE;
    public boolean isValidBST(TreeNode root) {
        if(root == null)
            return true;
        //the left sub tree
        if(isValidBST(root.left) == false)
            return false;
        //the current node
        if(root.val <= previous)
            return false;
        previous = root.val;
    
        
        //the right subtree
        if(isValidBST(root.right) == false){
            return false;
        }
        
        return true;
    }
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值