【发布时间】:2015-06-17 10:20:33
【问题描述】:
我似乎想不出解决这个问题的方法。至少不是一种优雅的方式。该函数应确定给定树是否为二叉搜索树。它似乎有效(但现在不允许重复)。
这是函数开始的地方:
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。
我将如何重写函数才能这样工作?还是有可能?
【问题讨论】:
标签: java recursion boolean binary-tree binary-search-tree