当前位置:网站首页>leetcode:297. Serialization and deserialization of binary tree
leetcode:297. Serialization and deserialization of binary tree
2022-07-03 03:57:00 【uncle_ ll】
297. Serialization and deserialization of binary trees
source : Power button (LeetCode)
Serialization is the operation of converting a data structure or object into consecutive bits , Then the transformed data can be stored in a file or memory , It can also be transmitted to another computer environment through the network , Reconstruct the original data in the opposite way .
Please design an algorithm to realize the serialization and deserialization of binary tree . There's no limit to your sequence / Deserialization algorithm execution logic , You just need to make sure that a binary tree can be serialized into a string and that the string can be deserialized into the original tree structure .
Tips : Input output format and LeetCode The current usage is consistent , Please refer to LeetCode The format of serializing binary tree . You don't have to do this , You can also use other methods to solve this problem .
Example 1:
Input :root = [1,2,3,null,null,4,5]
Output :[1,2,3,null,null,4,5]

Example 2:
Input :root = []
Output :[]
Example 3:
Input :root = [1]
Output :[1]
Example 4:
Input :root = [1,2]
Output :[1,2]
Tips :
- The number of nodes in the tree is in the range [0, 1 0 4 10^4 104] Inside
- -1000 <= Node.val <= 1000
solution
Serialization and deserialization of trees , Set the serialization rules and deserialization rules by yourself , Here, we take preorder traversal as the serialization rule , Root left and right ; There are two ways of preorder traversal, recursion and iteration , Here, recursion and sequence traversal are the solution methods .
recursive : Start at the root node , Then there is the left child node , Then there is the right child node , Finally, it is spliced into a string , Note that empty nodes should be saved in the middle ;
bfs loop : bfs Sequence traversal , First root node , Then the left and right nodes of the root node join the queue ;
Code implementation
recursive
python Realization
# 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 """
res = []
def helper(node):
if not node:
res.append(node)
else:
res.append(node.val)
helper(node.left)
helper(node.right)
helper(root)
string = ''
for node in res:
string += str(node) + ','
return string
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode """
def helper(ss):
if ss[0] == 'None':
ss.pop(0)
return None
root = TreeNode(ss.pop(0))
root.left = helper(ss)
root.right = helper(ss)
return root
return helper(data.split(','))
# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# ans = deser.deserialize(ser.serialize(root))
c++ Realization
/** * 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:
void reserialize(TreeNode* root, string& str) {
if (root == nullptr)
str += "None,";
else {
str += to_string(root->val) + ",";
reserialize(root->left, str);
reserialize(root->right, str);
}
}
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string ret;
reserialize(root, ret);
return ret;
}
TreeNode* rdeserialize(list<string>& dataAarray) {
if (dataAarray.front() == "None") {
dataAarray.erase(dataAarray.begin());
return nullptr;
}
TreeNode* root = new TreeNode(stoi(dataAarray.front()));
dataAarray.erase(dataAarray.begin());
root->left = rdeserialize(dataAarray);
root->right = rdeserialize(dataAarray);
return root;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
list<string> dataAarray;
string str;
for (auto& ch: data) {
if (ch == ',') {
dataAarray.push_back(str);
str.clear();
}
else
str.push_back(ch);
}
if (!str.empty()) {
dataAarray.push_back(str);
str.clear();
}
return rdeserialize(dataAarray);
}
};
// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));
Complexity analysis
- Time complexity : O ( N ) O(N) O(N) Each node is traversed once
- Spatial complexity : O ( N ) O(N) O(N) Recursive stack space per node
BFS loop
python Realization
# 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 '[]'
# bfs
res = []
queue = [root]
while queue:
node = queue.pop(0)
res.append(node.val) if node else res.append('null')
if node:
queue.append(node.left) if node.left else queue.append(None)
queue.append(node.right) if node.right else queue.append(None)
res = [str(i) for i in res]
while res[-1] == 'null':
res.pop()
return '[' + ','.join(res) + ']'
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode """
if data == '[]':
return None
vals = data[1: -1].split(',')
root = TreeNode(int(vals[0]))
i = 1
queue = [root]
length = len(vals)
while queue:
node = queue.pop(0)
if i < length and vals[i] != 'null':
node.left = TreeNode(int(vals[i]))
queue.append(node.left)
i += 1
if i < length and vals[i] != 'null':
node.right = TreeNode(int(vals[i]))
queue.append(node.right)
i += 1
return root
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
c++ Realization
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
// Sequence traversal BFS
string ret;
queue<TreeNode*> que;
que.emplace(root);
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
// Empty nodes join directly "None,"
if (node == NULL) ret += "None,";
else {
// Join node val, And traverse the left and right subtrees in turn
ret += to_string(node->val) + ",";
que.emplace(node->left);
que.emplace(node->right);
}
}
}
return ret;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if (data.size() == 0) return NULL;
list<string> dataArray;
string str;
for (auto& c : data) {
if (c == ',') {
dataArray.emplace_back(str);
str.clear();
} else {
str.push_back(c);
}
}
if (str.size() != 0) {
dataArray.emplace_back(str);
str.clear();
}
queue<TreeNode*> que;
if (dataArray.front() == "None") return NULL;
TreeNode* root = new TreeNode(stoi(dataArray.front()));
que.emplace(root);
dataArray.pop_front();
while (!que.empty() && !dataArray.empty()) {
int size = que.size();
for (int i = 0; i < size && !dataArray.empty(); i++) {
TreeNode* cur = que.front(); // Parent node
que.pop();
// The first is the left node
if (dataArray.front() != "None") {
TreeNode* node1 = new TreeNode(stoi(dataArray.front()));
cur->left = node1;
que.push(node1);
}
dataArray.pop_front();
// The second is the right node
if (dataArray.front() != "None") {
TreeNode* node2 = new TreeNode(stoi(dataArray.front()));
cur->right = node2;
que.push(node2);
}
dataArray.pop_front();
}
}
return root;
}
};
Complexity analysis
- Time complexity : O ( N ) O(N) O(N)
- Spatial complexity : O ( N ) O(N) O(N)
边栏推荐
- redis在服务器linux下的启动的相关命令(安装和配置)
- Mutex and rwmutex in golang
- [mathematical logic] propositional logic (judgment of the correctness of propositional logic reasoning | formal structure is eternal truth - equivalent calculus | deduction from premise - logical reas
- [Apple Push] IMessage group sending condition document (push certificate) development tool pushnotification
- FileZilla Client下载安装
- leetcode:动态规划模板
- js/ts底层实现双击事件
- The latest analysis of the main principals of hazardous chemical business units in 2022 and the simulated examination questions of the main principals of hazardous chemical business units
- In Net 6 project using startup cs
- Separable bonds and convertible bonds
猜你喜欢

pytorch开源吗?

PHP generates PDF tcpdf

MySQL MAC download and installation tutorial

2022 polymerization process examination questions and polymerization process examination skills
![[home push IMessage] software installation virtual host rental tothebuddy delay](/img/e7/eb20a773e4b674962f856d179a3769.jpg)
[home push IMessage] software installation virtual host rental tothebuddy delay

Esp32 series (3): GPIO learning (take simple GPIO input and output, ADC, DAC as examples)

Ffmpeg recording screen and screenshot

Is pytorch difficult to learn? How to learn pytorch well?

Error in compiled file: error: unmapped character encoding GBK

2022 tea master (intermediate) examination questions and analysis and tea master (intermediate) practical examination video
随机推荐
vim 的实用操作
在 .NET 6 项目中使用 Startup.cs
[home push IMessage] software installation virtual host rental tothebuddy delay
How to download pytorch? Where can I download pytorch?
8.8.2-PointersOnC-20220214
SAP UI5 应用开发教程之一百零五 - SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍
可分离债券与可转债
How to move towards IPv6: IPv6 Transition Technology - Shangwen network quigo
Shardingsphere dynamic data source
FileZilla Client下載安裝
pytorch怎么下载?pytorch在哪里下载?
Intercept string fixed length to array
学会pytorch能干什么?
编译文件时报错:错误: 编码GBK的不可映射字符
Makefile demo
[daily question] dichotomy - find a single dog (Bushi)
2022 mobile crane driver examination registration and mobile crane driver operation examination question bank
[mathematical logic] propositional logic (propositional and connective review | propositional formula | connective priority | truth table satisfiable contradiction tautology)
Without sxid, suid & sgid will be in danger- Shangwen network xUP Nange
[mathematical logic] propositional logic (equivalent calculus | idempotent law | exchange law | combination law | distribution law | De Morgan law | absorption rate | zero law | identity | exclusion l