import { concat, sum } from './array'; export type Tree = { node: T, children: Forest; }; export type Forest = Tree[]; export function createLeaf(node: T): Tree { return { node, children: [] }; } export function createTree(node: T, children: Forest): Tree { return { node, children }; } export function hasChildren(t: Tree): boolean { return t.children.length !== 0; } export function preorder(t: Tree): T[] { return [t.node, ...preorderF(t.children)]; } export function preorderF(ts: Forest): T[] { return concat(ts.map(preorder)); } export function countNodes(t: Tree): number { return preorder(t).length; } export function countNodesF(ts: Forest): number { return sum(ts.map(countNodes)); }