Startup VO 面试真题解析:二叉树序列化与反序列化

17次阅读
没有评论

Given a binary tree, create two functions: one that serializes the binary tree into a string and one that deserializes a serialized string back into a binary tree.

Example:

        1
       / \
      2   3
         / \
        4   5

Serialized string: 1,2,3,null,null,4,5,null,null,null,null

这道题考察二叉树的前序或层序序列化 / 反序列化设计,核心是用一个明确的空节点标记(如 null)来保留树结构信息。序列化时需要按固定遍历顺序把节点值与空指针一起写入字符串;反序列化时则按相同顺序逐个读取并重建左右子树。面试中常见的做法是使用 DFS 递归或 BFS 队列实现,重点在于保证编码和解码的顺序完全一致,从而准确还原原树。

正文完
 0