Skip to content

N-ary Trees

Question

Define N-ary trees and provide an implementation in Python.

Definition

Each node can have any number of children.

Example

   A
 / | \
B  C  D
  / \
 E   F

Implementation

from dataclasses import dataclass, field

@dataclass
class NaryNode:
    val: str
    children: list["NaryNode"] = field(default_factory=list)

root = NaryNode("A", [
    NaryNode("B"),
    NaryNode("C", [NaryNode("E"), NaryNode("F")]),
    NaryNode("D"),
])

Key trick

Store children in a list.

Trap

Do not use mutable default []; use default_factory=list.

Use

File systems, org charts, DOM-like structures.