4-26 树rust-2
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user