当前位置:网站首页>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)
边栏推荐
- How to move towards IPv6: IPv6 Transition Technology - Shangwen network quigo
- Role of JS No
- Dynamic programming: Longest palindrome substring and subsequence
- MySQL MAC download and installation tutorial
- FileZilla client download and installation
- 简易版 微信小程序开发之for指令、上传图片及展示效果优化
- Bisher - based on SSM pet adoption center
- pytorch项目怎么跑?
- [daily question] dichotomy - find a single dog (Bushi)
- Wechat applet + Alibaba IOT platform + Hezhou air724ug built with server version system analysis
猜你喜欢
JMeter starts from zero (III) -- simple use of regular expressions
For instruction, uploading pictures and display effect optimization of simple wechat applet development
Application of I2C protocol of STM32F103 (read and write EEPROM)
没有sXid,suid&sgid将进入险境!-尚文网络xUP楠哥
2022 tea master (intermediate) examination questions and analysis and tea master (intermediate) practical examination video
pytorch开源吗?
Leetcode: dynamic planning template
递归:快速排序,归并排序和堆排序
Esp32 series (3): GPIO learning (take simple GPIO input and output, ADC, DAC as examples)
2022-07-02:以下go语言代码输出什么?A:编译错误;B:Panic;C:NaN。 package main import “fmt“ func main() { var a =
随机推荐
学会pytorch能干什么?
leetcode:297. 二叉树的序列化与反序列化
2022 mobile crane driver examination registration and mobile crane driver operation examination question bank
递归:快速排序,归并排序和堆排序
Recursive use and multi-dimensional array object to one-dimensional array object
Commands related to the startup of redis under Linux server (installation and configuration)
[learning notes] seckill - seckill project - (11) project summary
Bisher - based on SSM pet adoption center
可分离债券与可转债
2022deepbrainchain biweekly report no. 104 (01.16-02.15)
第十届中国云计算大会·中国站:展望未来十年科技走向
没有sXid,suid&sgid将进入险境!-尚文网络xUP楠哥
Debug: CD cannot be used in kaggle
PHP generates PDF tcpdf
SAP ui5 application development tutorial 105 - detailed introduction to the linkage effect implementation of SAP ui5 master detail layout mode
Dynamic programming: longest common substring and longest common subsequence
以两列的瀑布流为例,我们应该怎么构建每一列的数组
How to download pytorch? Where can I download pytorch?
在 .NET 6 项目中使用 Startup.cs
Wechat applet + Alibaba IOT platform + Hezhou air724ug built with server version system analysis