(肝了三个小时的困难题-必须记录一下)剑指 Offer 37. 序列化二叉树-----python && C++源代码

简介: (肝了三个小时的困难题-必须记录一下)剑指 Offer 37. 序列化二叉树-----python && C++源代码

剑指 Offer 37. 序列化二叉树


难度困难306收藏分享切换为英文接收动态反馈


请实现两个函数,分别用来序列化和反序列化二叉树。


你需要设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。


提示:输入输出格式与 LeetCode 目前使用的方式一致,详情请参阅 LeetCode 序列化二叉树的格式。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。


示例:


image.png


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

输出:[1,2,3,null,null,4,5]

题目思路:

对于我们之前的前序遍历,中序遍历,后序遍历,均没有将null 这个存入我们的数组,因此在这里我们采用层序遍历对于无法访问的空值,存入null到数组即可。


感觉遵循这个思想还是,蛮简单的(但是细节的地方很多,具体看代码把 肝了好久)


Python代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Codec:
    def serialize(self, root):
        """Encodes a tree to a single string.
        :type root: TreeNode
        :rtype: str
        """
        if not root: return '[]'
        queue = collections.deque()
        queue.append(root)
        res = []
        while queue:
            node = queue.popleft()
            if node:
                res.append(str(node.val))
                queue.append(node.left)
                queue.append(node.right)
            else: res.append('null') 
        return '[' + ','.join(res) + ']'
    def deserialize(self, data):
        """Decodes your encoded data to tree.
        :type data: str
        :rtype: TreeNode
        """
        if data=='[]': return
        vals , i = data[1:-1].split(',') , 1
        root = TreeNode(int(vals[0]))
        queue = collections.deque()
        queue.append(root)
        while queue:
            ans_node = queue.popleft()
            if vals[i]!='null':
                ans_node.left = TreeNode(int(vals[i]))
                queue.append(ans_node.left)
            i += 1
            if vals[i]!='null':
                ans_node.right = TreeNode(int(vals[i]))
                queue.append(ans_node.right)
            i += 1
        return root


C++代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
public:
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string res;
        if(!root) return res;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            TreeNode* node = q.front();
            q.pop();
            if(node){
                res += to_string(node->val) + ",";  //获取当前节点的值放入res
                q.push(node->left); //先将左节点的值压入队列
                q.push(node->right);  //又节点的值压入队列
            }
            else res += "null,";
        }
        return res.substr(0 , res.size() - 1);
    }
    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        if(data.empty())  return nullptr;
        vector<string> s = split(data);
        queue<TreeNode*> q;
        TreeNode* root = new TreeNode(stoi(s[0]));// stoi函数 将n进制的字符串转化为十进制
        q.push(root);
        int i = 1;
        while (!q.empty()){
            TreeNode* node = q.front();
            q.pop();
            if (s[i]!="null"){
                node->left = new TreeNode(stoi(s[i]));
                q.push(node->left);
            }
            i++;
            if (s[i]!="null"){
                node->right = new TreeNode(stoi(s[i]));
                q.push(node->right);
            }
            i++;
        }
        return root;
    }
    vector<string> split(string& s){
        vector<string> res;
        int n = s.size();
        int i = 0;
        while (i<n){
             int j = i+1;
             while (j<n && s[j] != ',') j++;
             res.push_back(s.substr(i , j-i));
             i = j + 1; 
        }
        return res;
    }
};
相关文章
|
13天前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
27 6
|
14天前
|
Python
【Leetcode刷题Python】114. 二叉树展开为链表
LeetCode上114号问题"二叉树展开为链表"的Python实现,通过先序遍历二叉树并调整节点的左右指针,将二叉树转换为先序遍历顺序的单链表。
15 3
【Leetcode刷题Python】114. 二叉树展开为链表
|
13天前
|
索引 Python
【Leetcode刷题Python】从列表list中创建一颗二叉树
本文介绍了如何使用Python递归函数从列表中创建二叉树,其中每个节点的左右子节点索引分别是当前节点索引的2倍加1和2倍加2。
16 7
|
14天前
|
存储 算法 Python
【Leetcode刷题Python】297. 二叉树的序列化与反序列化
LeetCode第297题"二叉树的序列化与反序列化"的Python语言解决方案,包括序列化二叉树为字符串和反序列化字符串为二叉树的算法实现。
15 5
|
14天前
|
Python
【Leetcode刷题Python】236. 二叉树的最近公共祖先
LeetCode上236号问题"二叉树的最近公共祖先"的Python实现,使用递归方法找到两个指定节点的最近公共祖先。
23 5
|
13天前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - II. 从上到下打印二叉树 II
本文提供了一种Python实现方法,用于层次遍历二叉树并按层打印结果,每层节点按从左到右的顺序排列,每层打印到一行。
24 3
|
14天前
|
Python
【Leetcode刷题Python】199. 二叉树的右视图
LeetCode上199号问题"二叉树的右视图"的Python实现,通过深度优先搜索算法按层序从右向左访问节点,以获取每层的最右边节点的值。
15 4
|
13天前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - I. 从上到下打印二叉树
本文介绍了使用Python实现从上到下打印二叉树的解决方案,采用层次遍历的方法,利用队列进行节点的访问。
20 2
|
14天前
|
Python
【Leetcode刷题Python】105. 从前序与中序遍历序列构造二叉树
LeetCode上105号问题"从前序与中序遍历序列构造二叉树"的Python实现,通过递归方法根据前序和中序遍历序列重建二叉树。
13 3
|
14天前
|
存储 Python
【Leetcode刷题Python】103. 二叉树的锯齿形层序遍历
LeetCode上103号问题"二叉树的锯齿形层序遍历"的Python实现,使用了双端队列来实现层与层之间交替的遍历顺序。
11 3