这是一个家庭作业问题,所以我真正想要的是一个基本的递归算法。我正在研究 AATree 的地板/天花板方法。我当前的树有这样的结构:
40
20 60
10 30 50 80
70 90
100
(等级顺序)。我的 floor 方法有一个迭代解决方案:
/**
* Returns the greatest element in the set <= the_target.
* Strings are compared by ASCII values.
*
* @param the_target Element to compare set values with.
* @return Greatest element <= the_target, null if no such element exists.
*/
public E floor(final E the_target) {
AANode<E> current_node = my_root;
E result = null;
int root_value = compare(current_node.my_element, the_target);
while (true) {
if (root_value == 0) {
if (current_node.my_left.equals(my_null_node)
&& current_node.my_right.equals(my_null_node)) {
break;
}
result = current_node.my_element;
break;
}
if (contains(the_target)) {
result = the_target;
break;
} else if (root_value > 0) {
if (current_node.my_left.my_element == null) {
break;
}
current_node = current_node.my_left;
root_value = compare(current_node.my_element, the_target);
} else {
if (current_node.my_right.my_element == null) {
result = current_node.my_element;
break;
}
result = current_node.my_element;
current_node = current_node.my_right;
root_value = compare(current_node.my_element, the_target);
}
}
return result;
}
但我想让我的 ceiling() 方法递归。它必须具有此方法签名:
/**
* Returns the smallest element in the set >= the_target.
*
* @param the_target Element to compare set values with.
* @return Smallest element >= the_target, null if no such element exists.
*/
public E ceiling(final E the_target);
我将使用返回 E 的辅助递归方法来实现这一点。我试图让我的逻辑正确,并希望得到一些算法建议。
感谢大家的帮助!我知道了。
/**
* Helper recursive method for ceiling().
*
* @param the_root The current node.
* @param the_smallest The previous smallest element.
* @param the_target The target for ceiling.
* @return The ceiling element of the tree.
*/
private E findCeiling(final AANode<E> the_root, final AANode<E> the_smallest,
final E the_target) {
AANode<E> small = the_smallest;
if (compare(the_target, small.my_element) > 0) {
small = the_root;
}
// base case
if (the_root.my_left.my_element == null
&& the_root.my_right.my_element == null) {
return small.my_element;
} else {
if (compare(the_target, the_root.my_element) > 0) {
if (compare(the_smallest.my_element, the_root.my_element) > 0) {
small = the_root;
}
return findCeiling(the_root.my_right, small, the_target);
} else {
if (compare(the_smallest.my_element, the_root.my_element) > 0) {
small = the_root;
}
return findCeiling(the_root.my_left, small, the_target);
}
}
}