java - boolean 递归的替代方法

标签 java recursion boolean binary-tree binary-search-tree

我似乎想不出解决这个问题的方法。至少不是一种优雅的方式。该函数应确定给定树是否为二叉搜索树。它似乎有效(虽然现在不允许重复)。

这是函数开始的地方:

isBinarySearchTree(根)

功能:

public static boolean isBinarySearchTree(Node node) {

    if (node.leftchild != null) {
        if (node.leftchild.key < node.key)
            isBinarySearchTree(node.leftchild);
        else {
            System.out.println("false: " + node + " -> " + node.leftchild);
            return false;
        }
    }

    if (node.rightchild != null) {
        if (node.rightchild.key > node.key)
            isBinarySearchTree(node.rightchild);
        else {
            System.out.println("false: " + node + " -> " + node.rightchild);
            return false;
        }
    }

    return true;
}

显然我要返回的方式有问题。如果所有 boolean 返回值都在逻辑 && 链中,这将起作用。只有当所有返回值都为真时,返回值才应该为 true

我如何重写函数才能像那样工作?或者有可能吗?

最佳答案

我想这应该可行:

public static boolean isBinarySearchTree(Node node, int key) {
    if (node.leftchild != null && node.leftchild.key < key || node.rightchild != null && node.rightchild.key > key) {
        return false;
    } else {
        return (node.leftchild != null ? isBinarySearchTree(node.leftchild, node.leftchild.key) : true) && (node.rightchild != null ? isBinarySearchTree(node.rightchild, node.rightchild.key) : true);
    }
}

关于java - boolean 递归的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29582750/

相关文章:

Java:如何使用 URL.openConnection() 强制进行新的 SSL 握手?

algorithm - 如果基本情况是 O(n),则递归是多少?

c++ - 关于尾递归优化

python - 如何跟踪列表中的所有字符串是否都存在特定字符串?

java - 在 testng 中使用不同的数据提供者运行相同的测试

java - Android 位置管理器需要很长时间查找经度和纬度

java - 递归随机枢轴排序的问题

c - 这个方法声明有什么问题?

python - 根据字典检查数据帧值(作为键,值元组)的矢量化方法?

java - 有没有办法在 Spring MVC 测试中不使用 @MockBean?