布尔递归的java替代方案
我似乎想不出解决这个问题的办法。至少不是优雅的方式。函数应该确定给定的树是否是二叉搜索树。这似乎有效(不过现在不允许复制)
这是函数开始的地方:
isBinarySearchTree(root)
功能:
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;
}
很明显,我想要回来的方式有问题。如果所有的布尔返回值都在逻辑&&
链中,那么这将起作用。只有在所有返回值都为真时,返回值才应为true
我要如何重写函数才能这样工作?或者这有可能吗
共 (0) 个答案