Dev Helpers
← Back

Calculate tree height

Calculate tree height using TypeScript.

Open this example in the interactive library

Source code

type Tree = { label: string; children: Tree[] };
const root: Tree = {
  label: "src",
  children: [
    { label: "app", children: [{ label: "ui", children: [] }] },
    { label: "lib", children: [] },
  ],
};
console.log(
  (() => {
    function height(t: Tree): number {
      return 1 + Math.max(0, ...t.children.map(height));
    }
    return height(root);
  })(),
);

Sample output

3