【问题标题】:I dont understand how this is not a valid BST, can someone explain?我不明白这不是有效的 BST,有人可以解释一下吗?
【发布时间】:2021-06-02 18:54:51
【问题描述】:

Click for BST image

您好,我是初学者,现在正在学习 DSA。该程序用于验证 bst。在附加的图像中,所有左节点都小于它们的根节点,所有右节点都大于它们的根节点。但是根据编译器(leet 代码),预期的输出是错误的,我不明白为什么。有人可以向我解释一下吗?也请在下面找到我的代码。


class Solution {
    public boolean validatebst(TreeNode root){
        System.out.println("Traversing "+ root.val);
        if(root.left !=null && root.left.val > root.val)
            return false;
        else if(root.right != null && root.right.val < root.val){
            return false;
        }
        return true;
    }
    public boolean checkbst(TreeNode root){
        if(root == null)
            return true;
        if(!this.checkbst(root.left))
            return false;
        if(!this.validatebst(root))
            return false;
        if(!this.checkbst(root.right))
            return false;
        return true;
    }
    public boolean isValidBST(TreeNode root) {
        if(this.checkbst(root))
            return true;
        return false;
        
    }
}

【问题讨论】:

    标签: data-structures graph tree binary-search-tree dsa


    【解决方案1】:

    这棵树是无效的,因为右侧的叶子小于根。即使它在其父级的左侧,这是正确的,但根右侧的所有内容都必须大于根。

    https://dev.to/adityavardhancoder/what-is-a-valid-binary-search-tree-4kgj 此链接中的示例 3 解释,希望这会有所帮助:)

    【讨论】:

    • 哦,好吧。知道了。该链接清楚地解释了我的疑问。谢谢!
    猜你喜欢
    • 2021-02-13
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多