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.id
string
Optional. The key name for the node's unique identifier. Defaults to "id".
pid
string
Optional. The key name for the node's parent identifier. Defaults to "pid".
children
string
Optional. The key name for the children array. Defaults to "children".
Returns
object
Returns a statistics object containing
total, leafCount, maxDepth, and minDepth properties.Changelog
No recent changes