[NeetCode 150] Serialize and Deserialize Binary Tree

Serialize and Deserialize Binary Tree

Implement an algorithm to serialize and deserialize a binary tree.

Serialization is the process of converting an in-memory structure into a sequence of bits so that it can be stored or sent across a network to be reconstructed later in another computer environment.

You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. There is no additional restriction on how your serialization/deserialization algorithm should work.

Note: The input/output format in the examples is the same as how NeetCode serializes a binary tree. You do not necessarily need to follow this format.

Example 1:

Input: root = [1,2,3,null,null,4,5]

Output: [1,2,3,null,null,4,5]

Example 2:

Input: root = []

Output: []

Constraints:

0 <= The number of nodes in the tree <= 1000.
-1000 <= Node.val <= 1000

Solution

A classic problem to rebuild a tree from serialized data is building a tree from pre-order traversal and in-order traversal. To do this, we can use recursion function to dive into the subsequence of pre-order and in-order traversal. The first node in pre-order sequence must the root, and the sequence on the left of root in the in-order sequence must be the left child tree of the root, so as the sequence on the right.

However, if we rethink about the process. Why cannot we rebuild the tree only from pre-order traversal? That's because we cannot divide the sequences of the left child tree and right child tree. So, we need to mark where the left child tree ends by adding none nodes. If meet none nodes in DFS, it is time to return. By doing this, we can know where the left child tree ends and start to DFS the right child tree.

Code

Rebuild from pre-order and in-order traversal.

py 复制代码
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Codec:
    
    # Encodes a tree to a single string.
    def serialize(self, root: Optional[TreeNode]) -> str:
        if not root:
            return ''
        preo = []
        ino = []
        def inorder(node):
            if node.left:
                inorder(node.left)
            ino.append(str(node.val))
            if node.right:
                inorder(node.right)
        
        def preorder(node):
            preo.append(str(node.val))
            if node.left:
                preorder(node.left)
            if node.right:
                preorder(node.right)
        
        preorder(root)
        prestr = ','.join(preo)
        inorder(root)
        instr = ','.join(ino)
        return prestr+'#'+instr

        
    # Decodes your encoded data to tree.
    def deserialize(self, data: str) -> Optional[TreeNode]:
        if len(data) == 0:
            return None
        preorder = data.split('#')[0].split(',')
        inorder = data.split('#')[1].split(',')
        pre_map = {}
        in_map = {}
        for i in range(len(preorder)):
            pre_map[preorder[i]] = i
            in_map[inorder[i]] = i
        
        def dfs(prele, preri, inle, inri):
            if prele == preri:
                return TreeNode(int(preorder[prele]), None, None)
            if prele > preri:
                return None
            root = preorder[prele]
            inrootpos = in_map[root]
            ls_size = inrootpos-inle
            rs_size = inri-inrootpos
            ls = dfs(prele+1, prele+ls_size, inle, inrootpos-1)
            rs = dfs(prele+ls_size+1, preri, inrootpos+1, inri)
            return TreeNode(int(root), ls, rs)
        
        return dfs(0, len(preorder)-1, 0, len(inorder)-1)

Rebuild by adding none node to pre-order traversal.

py 复制代码
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Codec:
    
    # Encodes a tree to a single string.
    def serialize(self, root: Optional[TreeNode]) -> str:
        res = []

        def dfs(node):
            if not node:
                res.append("N")
                return
            res.append(str(node.val))
            dfs(node.left)
            dfs(node.right)

        dfs(root)
        return ",".join(res)
        
    # Decodes your encoded data to tree.
    def deserialize(self, data: str) -> Optional[TreeNode]:
        vals = data.split(",")
        self.i = 0

        def dfs():
            if vals[self.i] == "N":
                self.i += 1
                return None
            node = TreeNode(int(vals[self.i]))
            self.i += 1
            node.left = dfs()
            node.right = dfs()
            return node

        return dfs()
相关推荐
鸡鸭扣1 小时前
Docker:3、在VSCode上安装并运行python程序或JavaScript程序
运维·vscode·python·docker·容器·js
paterWang1 小时前
基于 Python 和 OpenCV 的酒店客房入侵检测系统设计与实现
开发语言·python·opencv
东方佑2 小时前
使用Python和OpenCV实现图像像素压缩与解压
开发语言·python·opencv
神秘_博士2 小时前
自制AirTag,支持安卓/鸿蒙/PC/Home Assistant,无需拥有iPhone
arm开发·python·物联网·flutter·docker·gitee
Moutai码农3 小时前
机器学习-生命周期
人工智能·python·机器学习·数据挖掘
小白教程4 小时前
python学习笔记,python处理 Excel、Word、PPT 以及邮件自动化办公
python·python学习·python安装
武陵悭臾5 小时前
网络爬虫学习:借助DeepSeek完善爬虫软件,实现模拟鼠标右键点击,将链接另存为本地文件
python·selenium·网络爬虫·pyautogui·deepseek·鼠标右键模拟·保存链接为htm
代码猪猪傻瓜coding5 小时前
关于 形状信息提取的说明
人工智能·python·深度学习
码界筑梦坊6 小时前
基于Flask的第七次人口普查数据分析系统的设计与实现
后端·python·信息可视化·flask·毕业设计
微笑的Java7 小时前
Python - 爬虫利器 - BeautifulSoup4常用 API
开发语言·爬虫·python