← 中文资源

简体中文版本

递归树类型与深度优先折叠

children 字段引用节点自身类型即可递归定义树结构;一个泛型 foldTree 把每个子树的结果交给 combine 合并,同一套实现算出访问顺序、最大深度与叶子数。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

depth-first visit order: [ 'catalog', 'electronics', 'laptops', 'phones', 'books' ]
tree depth: 3
leaf count: 3

实现说明

全部逻辑都在函数 foldTree中。

使用要点

  • 演示输出是带标签的(depth-first visit order:、tree depth:、leaf count:),每个操作都会留下自己的一行标注。

常见问题

复制和运行之间有安装步骤吗?

没有。从复制到运行之间没有别的要做。 文件在加载时定义 foldTree。

核心语句

const names = foldTree<string[]>(tree, (name, childPaths) => [
  name,
  ...childPaths.flat(),
]);
const leaves = foldTree<number>(tree, (_name, childCounts) =>
  childCounts.length === 0 ? 1 : childCounts.reduce((a, b) => a + b, 0),
);
const depth = foldTree<number>(tree, (_name, childDepths) =>
  childDepths.length === 0 ? 1 : 1 + Math.max(...childDepths),
);

代码示例

interface CategoryNode {
  name: string;
  children: CategoryNode[]; // recursive: the node type references itself
}

const tree: CategoryNode = {
  name: 'catalog',
  children: [
    {
      name: 'electronics',
      children: [
        { name: 'laptops', children: [] },
        { name: 'phones', children: [] },
      ],
    },
    { name: 'books', children: [] },
  ],
};

// Depth-first fold: recurse into children first, then combine the
// child results with this node's own name
function foldTree<T>(
  node: CategoryNode,
  combine: (name: string, childResults: T[]) => T,
): T {
  return combine(
    node.name,
    node.children.map((child) => foldTree(child, combine)),
  );
}

const names = foldTree<string[]>(tree, (name, childPaths) => [
  name,
  ...childPaths.flat(),
]);
console.log('depth-first visit order:', names);

const depth = foldTree<number>(tree, (_name, childDepths) =>
  childDepths.length === 0 ? 1 : 1 + Math.max(...childDepths),
);
console.log('tree depth:', depth);

const leaves = foldTree<number>(tree, (_name, childCounts) =>
  childCounts.length === 0 ? 1 : childCounts.reduce((a, b) => a + b, 0),
);
console.log('leaf count:', leaves);