ancestorsOf<T> static method

List<TreeNodeId> ancestorsOf<T>(
  1. List<TreeNode<T>> roots,
  2. TreeNodeId id
)

Ancestor ids of id, outermost-first (empty if root or missing).

Implementation

static List<TreeNodeId> ancestorsOf<T>(List<TreeNode<T>> roots, TreeNodeId id) {
  List<TreeNodeId>? result;
  void rec(List<TreeNode<T>> nodes, List<TreeNodeId> path) {
    for (final n in nodes) {
      if (n.id == id) {
        result = path;
        return;
      }
      if (n.children.isNotEmpty) rec(n.children, [...path, n.id]);
    }
  }

  rec(roots, const []);
  return result ?? const [];
}