【发布时间】:2020-06-20 21:20:16
【问题描述】:
如果我有一个方法只将值作为参数(不是节点),称为public Node finder (E val),无论树的高度和宽度如何,我如何才能找到相应的节点。如果该方法将 Node 作为参数,那么使用递归将是一个简单的解决方案。但不幸的是,我不允许更改方法签名。我怎样才能以聪明的方式而不是我在下面尝试的愚蠢方式来做到这一点,这最终会导致大量嵌入式 if 函数
public class BinarySearchTree<E extends Comparable<E>> {
class Node {
E value;
Node leftChild = null;
Node rightChild = null;
Node(E value) {
this.value = value;
}
}
public Node finder(E val) {
if (val == null) return null;
if (root == null) return null;
boolean flag = false;
Node temp = root;
//find if Root Node matches value
if(temp.value.compareTo(val) == 0) {
flag = true;
return temp;
}
//if value is less than root check the left branch
else if (temp.value.compareTo(val) > 0) {
if(temp.leftChild.value.compareTo(val) == 0) {
flag = true;
return temp.leftChild;
}
//more if statements here
}
//if value is more than root check the right branch
else {
if(temp.rightChild.value.compareTo(val) == 0) {
flag = true;
return temp.rightChild;
}
//more if statements here
}
return null;
}
}
【问题讨论】:
-
您始终可以将递归函数转换为迭代函数,其中包含显式
Stack<Node>并在其中推送“待访问节点” -
@roookeee 谢谢你的建议!您介意发布一个简短的代码示例,说明您将如何实施此解决方案吗?
标签: java tree binary-tree nodes