N-ary Trees
An N-ary tree is a tree where each node can have any number of children — not just two. While binary trees restrict each parent to at most 2 children, N-ary trees lift that restriction entirely.
Real-world examples are everywhere:
- File system — a folder can contain any number of files and subfolders
- HTML DOM — a
<div>can have dozens of child elements. A Trie is another specialized N-ary tree used for string prefix search - Organization chart — a manager can have any number of direct reports
- Comment threads — a comment can have any number of replies
- JSON/XML documents — nodes with variable numbers of children
Structure
An N-ary node typically looks like:
The children list grows dynamically — a node with 3 children stores 3 references, a leaf stores an empty list.
← → arrow keys to step · click elements to interact
N-ary Tree: Build & Traverse
Traversing an N-ary tree
The same traversal strategies apply as with binary trees, just adapted for variable numbers of children:
Pre-order (DFS)
Visit the current node, then recursively visit each child in order:
Post-order (DFS)
Visit all children first, then the current node:
Level-order (BFS)
Visit nodes level by level using a queue — same as binary tree BFS, just enqueue all children instead of just two:
Serialization and deserialization
Storing an N-ary tree to disk or sending it over a network requires serialization. One common approach: encode each node's value followed by a count of its children, then recursively serialize each child. Another approach: use a special null marker to separate siblings from the parent's end of children list.
The popular LeetCode encoding for N-ary trees uses a level-order format with null separators between levels.
N-ary tree vs. binary tree
When should you use each?
- Use a binary tree when your domain has a natural "two-way split" (less/greater, true/false) or you need BST search properties
- Use an N-ary tree when nodes naturally have a variable number of children (file systems, parse trees, org charts)
Height and depth
The height of an N-ary tree is the length of the longest root-to-leaf path. In a balanced N-ary tree with branching factor k, the height is \(O(log_k n)\) — which can be much smaller than a binary tree's \(\log_2(n)\). For example, a file system with average branching factor 20 can store millions of files in just 4-5 levels.