4-26 树rust-2

This commit is contained in:
lix-2026
2026-04-26 04:29:23 +08:00
parent 94631f3636
commit 338bb2e20f
58 changed files with 11718 additions and 1256 deletions
+23 -1
View File
@@ -3,6 +3,29 @@ export type ParentLinkedRow = {
parent_id?: string | null;
};
export function buildParentById<T extends ParentLinkedRow>(rows: readonly T[]): Map<string, string | null> {
const map = new Map<string, string | null>();
for (const row of rows) {
map.set(row.id, row.parent_id ?? null);
}
return map;
}
export function isAncestorOf(
ancestorId: string,
nodeId: string,
parentById: Map<string, string | null>,
): boolean {
let current: string | null | undefined = nodeId;
while (current) {
const parentId = parentById.get(current);
if (!parentId) return false;
if (parentId === ancestorId) return true;
current = parentId;
}
return false;
}
/**
* 收集以 rootId 为根的整棵子树(包含根节点本身)。
*
@@ -41,4 +64,3 @@ export function collectSubtree<T extends ParentLinkedRow>(rows: readonly T[], ro
return result;
}