我有這個函式,我想回傳大于或等于給定節點的最小節點,如果沒有這樣的節點,則回傳 NULL。
我寫了這個偽代碼
// searches for the smallest node greater than or equal to a given node
static Node doTreeNext(Tree t, Node n, Node target) {
// no record greater
if (n == NULL) {
return NULL;
}
if (n > target) {
return doTreenNext(t, n->left, target);
} else if (n <= target) {
return doTreenNext(t, n->right, target);
}
}
問題是如果我有一棵像下面這樣的樹
https://i.stack.imgur.com/U8pEI.png
目標節點為 12 時的預期輸出為 13。該函式當前將回傳 NULL,因為
13 > 12(向左搜索) 11 < 12(向右搜索,為 NULL)
我的問題是如何在 13 點停止它?
uj5u.com熱心網友回復:
每次您點擊一個大于您的目標值的節點時,您就有一個潛在的答案候選者,除非遞回應答呼叫不會導致 null,否則應該采用該候選者。
你應該有類似下面的偽代碼:
if (n > target) {
candidate = search(n->left);
if (candidate is null) {
return n;
}
else {
return candidate;
}
}
else {
return search(n->right);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/512701.html
