getStats

Compute statistics for a tree, including total nodes, leaves, branches, and maximum depth, to summarize its size and shape.

Usage

The getStats method traverses the entire tree and returns an object containing its statistics.

example.ts
import { Tree } from '@movk/core'

const tree = [
  { id: 1, children: [
    { id: 2 },
    { id: 3, children: [{ id: 4 }] }
  ] }
]

const stats = Tree.getStats(tree)

/*
stats will be:
{
  total: 4,     // total number of nodes
  leafCount: 2, // number of leaf nodes
  maxDepth: 2,  // maximum depth
  minDepth: 1   // minimum depth (among leaf nodes)
}
*/

API

getStats<T extends TreeNode>(tree: T[], config?: TreeConfig): { total: number; leafCount: number; maxDepth: number; minDepth: number }

Parameters

tree
T[] required
The source tree array.
config
TreeConfig
Configuration object for customizing the id, pid, children key names in the tree structure.

Returns

object
Returns a statistics object containing total, leafCount, maxDepth, and minDepth properties.

Changelog

No recent changes
Copyright © 2024 - 2026 YiXuan - MIT License