⚡Flashcard Drill➔
NeetCode #414LC-428HardTreesNC Algo100
← Back to All Problems

#414 · #428 · Serialize and Deserialize N-ary Tree(序列化和反序列化 N 叉树)

📌 Problem Statement & Constraints

Design an algorithm to serialise and deserialise an N-ary tree. Constraints: the number of nodes is in [0, 10^4], 0 <= Node.val <= 10^4, the depth is at most 1000.

💡 Core Algorithmic Approaches

  1. A pre-order traversal with an explicit child count per node is unambiguous.
  2. Serialise each node as <value>,<child count> followed by its children's encodings.
  3. Deserialise by consuming the tokens in the same order: read the value and the child count, then recursively build that many children.
  4. The child count is what replaces the null markers used in the binary-tree version.

💻 Benchmark Python3 Implementation

class Codec:
    def serialize(self, root: "Optional[Node]") -> str:
        if not root:
            return ""
        parts = []

        def dfs(node: "Node") -> None:
            parts.append(str(node.val))
            parts.append(str(len(node.children)))   # child count disambiguates
            for c in node.children:
                dfs(c)

        dfs(root)
        return ",".join(parts)

    def deserialize(self, data: str) -> "Optional[Node]":
        if not data:
            return None
        tokens = iter(data.split(","))

        def build() -> "Node":
            val = int(next(tokens))
            n = int(next(tokens))                   # how many children follow
            node = Node(val, [])
            for _ in range(n):
                node.children.append(build())
            return node

        return build()

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n) for both directions.
💾 Space Complexity
O(n) for the token list plus O(h) for the recursion.

⚠️ Interview Pitfalls & Follow-ups

  • Omitting the child count: the structure would be ambiguous, since an N-ary tree has no null markers between siblings.
  • Using a fixed-width encoding: values are not bounded in length, so a delimiter is required.
  • Consuming tokens out of order: the recursion must share a single iterator so the pre-order sequence is respected.
  • Recursing on a depth-1000 tree: within Python's default limit, but a stack-based version would be safer.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Trees Problems

中文速览与面试要点

序列化和反序列化 N 叉树

序列化是指将一个数据结构转化为位序列的过程,因此可以将其存储在文件中或内存缓冲区中,以便稍后在相同或不同的计算机环境中恢复数据结构。设计一个序列化和反序列化 N 叉树的算法。一个 N 叉树是指每个节点都有不超过 N 个孩子节点的有向无环图结构。序列化 / 反序列化算法的工作方式没有限制。你只需保证 N 叉树能序列化成字符串,并且该字符串能反序列化回原 N 叉树。约束:树中节点数目的范围是 [0, 10^4];0 ≤ Node.val ≤ 10^4;N 叉树的高度小于等于 1000;不要使用类成员 / 全局变量 / 静态变量来存储状态。

核心要点

  • 前序 + 子节点个数(标准解) :序列化时对每个节点输出「节点值 子节点个数」,然后递归序列化每个子节点。
  • 为什么必须记录子节点个数 :反序列化时若不知道有几个子节点,就无法确定递归边界。
  • 反序列化用迭代器 : iter(data.split()) ,每次 next 取值,递归消费。
  • 空树的表示 :返回空字符串,反序列化时判空返回 None。

常见陷阱

  • 不记录子节点个数 :反序列化无法确定边界,必须显式存储。
  • 用逗号分隔而非空格 :本题节点值都是数字,空格分隔足够;若值可能含空格则需转义。
  • 忘记处理空树 :序列化返回空串,反序列化需判空。
  • 递归深度过大 :树高可达 1000,接近 Python 递归上限。

参考实现

class Codec:
    def serialize(self, root: 'Node') -> str:
        if not root:
            return ''
        out = [str(root.val), str(len(root.children))]
        for c in root.children:
            out.append(self.serialize(c))
        return ' '.join(out)

    def deserialize(self, data: str) -> 'Node':
        if not data:
            return None
        vals = iter(data.split())
        def build():
            val = int(next(vals))
            n = int(next(vals))             # 子节点个数
            node = Node(val, [])
            node.children = [build() for _ in range(n)]
            return node
        return build()