[英]how to find lowest common ancestor of a nary tree?
有沒有一種方法可以不使用額外空間來找到 nary 樹的 LCA。 我使用一個字符串來保存兩個節點的預序並找到公共前綴
如果節點“知道”它們的深度 - 或者您願意讓空間計算節點的深度,您可以從較低節點備份到較高節點的相同深度,然后 go 向上一級直到他們見面的時間。
取決於“額外空間”在這種情況下的含義。 你可以用一個 integer 來完成 - 兩個節點的深度差異。 空間太大了嗎?
另一種可能性是你沒有父指針,你可以使用指針反轉 - 每次遍歷指針時,記住你來自的位置,記住下一次遍歷的指針,然后在下一次指針遍歷之前, 將該指針替換為后向指針。 上樹恢復它時,您必須反轉它。 這將一個指針的空間作為臨時空間。 另一個 integer 可在您上下工作時保持深度。 對您尋找的兩個節點同步執行此操作,以便您可以從較低的節點向上返回,直到您在兩次遍歷中處於相同的高度,然后從兩個節點向上返回,直到您處於公共節點. 這需要三塊額外的 memory - 每個當前深度一個,一個用於指針反轉期間使用的臨時深度。 非常節省空間。 這值得么?
Go 返回並為二叉樹做。 如果你能為二叉樹做到這一點,那么你也能為 n 叉樹做到這一點。
下面是將其轉換為 n 元樹 LCA 后的樣子:
public class LCA {
public static <V> Node<V>
lowestCommonAncestor(Node<V> argRoot, Node<V> a, Node<V> b) {
if (argRoot == null) {
return null;
}
if (argRoot.equals(a) || argRoot.equals(b)) {
// if at least one matched, no need to continue
// this is the LCA for this root
return argRoot;
}
Iterator<Node<V>> it = argRoot.childIterator();
// nr of branches that a or b are on,
// could be max 2 (considering unique nodes)
int i = 0;
Node<V> lastFoundLCA = null;
while (it.hasNext()) {
Node<V> node = lowestCommonAncestor(it.next(), a, b);
if (node != null) {
lastFoundLCA = node;
i++ ;
}
if (i >= 2) {
return argRoot;
}
}
return lastFoundLCA;
}
}
對兩個節點進行同步步行。
C中的偽代碼:
struct node {
struct node *offspring[1234];
int payload;
};
/* compare function returning the slot in which this should be found/placed */
int find_index (struct node *par, struct node *this);
struct node *lca(struct node *root, struct node *one, struct node *two)
{
struct node *lca;
int idx1,idx2;
for (lca=root; lca; lca=lca->offspring[idx1] ) {
idx1 = find_index(lca, one);
idx2 = find_index(lca, two);
if (idx1 != idx2 || idx1 < 0) break;
if (lca->offspring[idx1] == NULL) break;
}
return lca;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.