【发布时间】:2016-03-31 05:12:23
【问题描述】:
我正在编写一个 Java 方法,该方法采用二叉搜索树 (BST) T 和键 k,并返回大于 k 的第一个条目,该条目将出现在中序遍历中。如果 k 不存在或不存在大于 k 的键,则返回 null。例如,当应用于下图中的 BST 时,如果 k = 23,则应返回 29;如果 k = 32,则应返回 null。
伪代码为:
findFirstEntryLargerThanKey(BSTNode t, int key)
// go left
findFirstEntryLargerThanKey(t.left, key);
// visit the node
if t.nodeValue == key
key exists, set a boolean value to true
else if t.nodeValue > key
check if this node value is the first entry larger than key
// go right
findFirstEntryLargerThanKey(t.right, key);
我写到现在的代码:
boolean found = false;
int x = 0;
public Integer findFirstEntryLargerThanKey(BSTNode t, int key) {
// the scan terminates on an empty subtree
if (t != null) {
// descend left
findFirstEntryLargerThanKey(t.left, key);
// visit the node
if (t.nodeValue == key){
found = true;
}
else if (t.nodeValue > key && found == true && ? && ?){
x = t.nodeValue;
}
// descend right
findFirstEntryLargerThanKey(t.right, key);
return x;
}
return null;
}
我需要有关我必须使用的条件的帮助。
【问题讨论】:
-
那么问题是什么?
-
@Guy 他可能想用什么条件代替'?'s
-
@TechSpellBound 如果那是 OP 想要的,他/她需要说出来。
-
@Guy 同意了!
-
对不起,我需要帮助。