Leetcode 98. Validate Binary Search Tree

该博客讨论了一种使用递归方法检查二叉树是否符合有效二叉搜索树条件的算法。通过比较节点值与左右子树的最大值和最小值,确保每个节点满足BST规则。代码中定义了辅助函数来获取左子树的最大值和右子树的最小值,最后总结这是LC官方题目的一种经典解决方案。

在这里插入图片描述
方法1: recursion。直接按照题目给出的三个判定条件来check是否为valid bst。时间复杂nlogn(可能有错),空间复杂n。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        if(root.left == null && root.right == null) return true;
        boolean left = root.left != null ? isValidBST(root.left) : true; 
        boolean right = root.right != null ? isValidBST(root.right) : true; 
        if(!(left && right)) return false;
        int leftBiggest = 0;
        int rightSmallest = 0;
        if (root.left != null) leftBiggest = leftBiggest(root.left);
        if (root.right != null) rightSmallest = rightSmallest(root.right);
        if(root.left == null){
            if( root.val < rightSmallest) return true;
        }else if(root.right == null){
            if(root.val > leftBiggest ) return true;
        }else{
          if(root.val > leftBiggest && root.val < rightSmallest) return true;  
        } 
        return false;
    }
    
    public int leftBiggest(TreeNode root){
        TreeNode copy = root;
        while(copy.right != null){
            copy = copy.right;
        }
        return copy.val;
    }
    
    public int rightSmallest(TreeNode root){
        TreeNode copy = root;
        while(copy.left != null){
            copy = copy.left;
        }
        return copy.val;
    }
}

总结:

  • 这道题应该是很经典的一道题,lc官方解答我都没看呢,第二次做的时候一定要全部看一遍。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值