Java 为什么isBinarySearchTree()函数不正确

Java 为什么isBinarySearchTree()函数不正确,java,algorithm,recursion,tree,binary-tree,Java,Algorithm,Recursion,Tree,Binary Tree,我正在检查一棵树是否是二叉搜索树。我知道已知的解决方案是什么。在我查找它之前,我提出了以下基于后序遍历的尝试。我已经用手摸过了,似乎有道理。但是,这是不正确的。有人能帮我理解为什么吗 class Node { int data; Node left; Node right; } boolean checkBST(Node root) { // Empty tree if (root == null) { return true;

我正在检查一棵树是否是二叉搜索树。我知道已知的解决方案是什么。在我查找它之前,我提出了以下基于后序遍历的尝试。我已经用手摸过了,似乎有道理。但是,这是不正确的。有人能帮我理解为什么吗

class Node {
    int data;
    Node left;
    Node right;
 }

boolean checkBST(Node root) {

    // Empty tree
    if (root == null) {
        return true;
    }

    // Sub trees are BST
    boolean valid = checkBST(root.left) && checkBST(root.right);     

    // Greater than left
    if (root.left != null) {
        valid = valid && root.data > root.left.data;
    }

    // Less than right
    if (root.right != null) {
        valid = valid && root.data < root.right.data;
    }

    return valid;
}

对于此基本测试用例,您的代码将失败,因为对于以下情况,它将返回true:

    50 
   /
  3
 / \
1   100
问题是您的代码只是将节点与其直接子节点进行比较,而不是将其与整个子树进行比较。对于根为3和3的子树,它返回true
因为3<50,您的代码最终返回true,这是错误的。

我希望您现在看到错误。@Nelxiost很可能是java注意布尔关键字。@Nelxiost抱歉,这是java!我是在Hackerrank上做的。它是一个代码存根,所以我忘了粘贴语言,或者把它放到类文件中