当前位置:网站首页>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)
边栏推荐
- 【刷题篇】多数元素(超级水王问题)
- Esp32 series (3): GPIO learning (take simple GPIO input and output, ADC, DAC as examples)
- Ffmpeg download and installation tutorial and introduction
- Without sxid, suid & sgid will be in danger- Shangwen network xUP Nange
- [Blue Bridge Road - bug free code] pcf8591 - code analysis of AD conversion
- 2.14 simulation summary
- leetcode:动态规划模板
- [mathematical logic] propositional logic (propositional and connective review | propositional formula | connective priority | truth table satisfiable contradiction tautology)
- 【刷题篇】 找出第 K 小的数对距离
- Ffmpeg one / more pictures synthetic video
猜你喜欢

For instruction, uploading pictures and display effect optimization of simple wechat applet development

CEPH Shangwen network xUP Nange that releases the power of data

User value is the last word in the competition of mobile phone market

IPv6 transition technology-6to4 manual tunnel configuration experiment -- Kuige of Shangwen network

Table structure of Navicat export database

Nodejs Foundation: shallow chat URL and querystring module

小程序获取用户头像和昵称

Error in compiled file: error: unmapped character encoding GBK

简易版 微信小程序开发之页面跳转、数据绑定、获取用户信息、获取用户位置信息

Docker install and start MySQL service
随机推荐
Social phobia of contemporary young people (II)
Some preliminary preparations for QQ applet development: make an appointment for a development account, download and install developer tools, and create QQ applet
sigaction的使用
Web session management security issues
Use of sigaction
Cnopendata China Customs Statistics
简易版 微信小程序开发之页面跳转、数据绑定、获取用户信息、获取用户位置信息
Application of I2C protocol of STM32F103 (read and write EEPROM)
QSAR model establishment script based on pytoch and rdkit
What is the correct way to compare ntext columns with constant values- What's the right way to compare an NTEXT column with a constant value?
Idea shortcut keys
【学习笔记】seckill-秒杀项目--(11)项目总结
C语言HashTable/HashSet库汇总
JS native common knowledge
docker安装及启动mysql服务
IPv6 transition technology-6to4 manual tunnel configuration experiment -- Kuige of Shangwen network
2022 tea master (intermediate) examination questions and analysis and tea master (intermediate) practical examination video
Debug: CD cannot be used in kaggle
Mutex and rwmutex in golang
Docker install and start MySQL service