我在寫一個Java方法,它採用二叉搜索樹(BST)T和一個關鍵字k,並返回大於k的第一個條目,該條目將出現在inorder遍歷。如果k不存在或者沒有大於k的密鑰,則返回null。例如,當應用於下圖中的BST時,如果k = 23,則應該返回29;如果k = 32,則應該返回null。BST:返回大於關鍵字的第一個條目
的僞代碼爲:
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);
我寫uptil現在的代碼:
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
@Guy他可能想要使用什麼條件代替'?' – TechSpellBound
@TechSpellBound如果OP希望他/她需要說出什麼。 – Guy