【发布时间】:2016-03-29 09:13:02
【问题描述】:
所以我被困了好几个小时试图找出这个问题。
给定一个随机生成的 BST 并使用方法头:
public E higher(E elt)
其中elt 是树范围内随机生成的值,我需要找到集合中大于elt 的最小元素。
节点包含左链接和右链接,但没有父链接。
链接图像中的树以根为最左边的节点读取 BST.
所以如果elt是27,那么我想返回包含28的节点。
我需要在 O(logn) 时间内运行它,而我尝试过的一切都没有奏效。 我不是在找人帮我做作业,但我现在不知道该怎么做。
如果需要,我可以提供更多细节和源代码。
编辑:我会把它放在这里,尽管它非常不合适。我觉得如果我可以递归地执行此操作会更容易,但我想不出办法。
Node n = root;
//need to get this into a loop somehow and break out when I've found
//the right value
int c = myCompare(elt, ((E) n.data));
if (c < 0) {
n = n.left;
//now I need to compare this against any children
} else if (c > 0) {
n = n.right;
//now I need to compare this against any children
}
return ((E)n.data);
【问题讨论】:
-
如果您想了解更多关于可以做到这一点的方法,这也称为
ceiling函数。还有floor,它得到小于或等于给定元素的最高元素。