当前位置:网站首页>[sword finger offer] serialized binary tree
[sword finger offer] serialized binary tree
2022-07-06 08:50:00 【Broken wind boy who keeps his hair】
Their thinking
Serialization , You can use various traversal methods , For example, sequence traversal 、 Recursive traversal traverses the binary tree , The value of each node is spliced into a string during traversal , Note that each node is separated by an identifier , for example ,
, This is to prevent the value of the node from exceeding single digits .
Deserialization is decoded according to the serialization process , Different ways of deserialization have different skills , Next, sequence traversal and preorder traversal are used to solve .
Solution 1 : Sequence traversal
- serialize : Traverse through the queue , Then generate a serialized string , Comparing to conventional .
- Deserialization : It's a little bit difficult . First of all,
res
according to,
Get by segmentation String Arraystrs
, Each position represents the value of a node . Like serialization , You also need to use a queue to operate , Note that you need to get the array every timestrs
Two elements in , That is to build the left and right subtrees of the current node , Then add the left and right subtrees to the queue respectively .
import java.util.*;
public class Solution {
String Serialize(TreeNode root) {
String str = "";
if (root == null)
return str;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
str += root.val + ",";
while (!queue.isEmpty()) {
TreeNode top = queue.poll();
if (top.left == null)
str += "#";
else {
queue.add(top.left);
str += top.left.val;
}
str += ',';
if (top.right == null)
str += "#";
else {
queue.add(top.right);
str += top.right.val;
}
str += ',';
}
return str;
}
TreeNode Deserialize(String str) {
if (str.length() == 0)
return null;
int i = 1;
String strList[] = str.split(",");
TreeNode root = new TreeNode(Integer.parseInt(strList[0]));
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode top = queue.poll();
// The left subtree
if (strList[i].equals("#"))
top.left = null;
else {
top.left = new TreeNode(Integer.parseInt(strList[i]));
queue.add(top.left);
}
i++;
// Right subtree
if (strList[i].equals("#"))
top.right = null;
else {
top.right = new TreeNode(Integer.parseInt(strList[i]));
queue.add(top.right);
}
i++;
}
return root;
}
}
Solution 2 : The first sequence traversal
- serialize : Define global string
res
, Record the node value traversed during recursion , After traversing a node , Add... After it,
identifier . - Deserialization : It's a little bit difficult . First of all,
res
according to,
Get by segmentation String Arraystrs
, Each position represents the value of a node . Define global variablesind
, Used to record the current traversal tostrs
The location of , If the current location is#
, Said is empty , Go straight back tonull
; Otherwise, create a new nodenode
, And recursively construct its left and right subtrees , Be careful , Determine whether the array is out of bounds before recursion , Ifinds++
After equal tostrs
The length of , It indicates that the array has been traversed , Return at this timenode
( Note that the judgment of array out of bounds cannot be placed at the beginning , Otherwise, I can't write it down , Because I don't know what to return )
import java.util.*;
public class Solution {
public String res = "";
public int ind = 0;
String Serialize(TreeNode root) {
if (root == null) {
res += "#,";
return res;
}
res += root.val + ",";
Serialize(root.left);
Serialize(root.right);
return res;
}
TreeNode deserialize(String[] strs) {
if (strs[ind].equals("#")) {
ind++;
return null;
}
TreeNode node = new TreeNode(Integer.parseInt(strs[ind]));
ind++;
if (ind >= strs.length)
return node;
node.left = deserialize(strs);
node.right = deserialize(strs);
return node;
}
TreeNode Deserialize(String str) {
String[] strs = str.split(",");
return deserialize(strs);
}
}
边栏推荐
- Charging interface docking tutorial of enterprise and micro service provider platform
- [embedded] cortex m4f DSP Library
- Sublime text in CONDA environment plt Show cannot pop up the problem of displaying pictures
- Trying to use is on a network resource that is unavailable
- Double pointeur en langage C - - modèle classique
- Process of obtaining the electronic version of academic qualifications of xuexin.com
- LeetCode:39. 组合总和
- How to conduct interface test? What are the precautions? Nanny level interpretation
- 如何有效地进行自动化测试?
- Shift Operators
猜你喜欢
广州推进儿童友好城市建设,将探索学校周边200米设安全区域
swagger设置字段required必填
TP-LINK 企业路由器 PPTP 配置
Current situation and trend of character animation
Generator parameters incoming parameters
Mobile phones and computers on the same LAN access each other, IIS settings
vb.net 随窗口改变,缩放控件大小以及保持相对位置
生成器参数传入参数
C语言深度解剖——C语言关键字
win10系统中的截图,win+prtSc保存位置
随机推荐
可变长参数
poi追加写EXCEL文件
Bottom up - physical layer
TP-LINK enterprise router PPTP configuration
Target detection - pytorch uses mobilenet series (V1, V2, V3) to build yolov4 target detection platform
What are the common processes of software stress testing? Professional software test reports issued by companies to share
ESP8266-RTOS物联网开发
Revit 二次开发 HOF 方式调用transaction
C語言雙指針——經典題型
How to conduct interface test? What are the precautions? Nanny level interpretation
Marathon envs project environment configuration (strengthen learning and imitate reference actions)
如何进行接口测试测?有哪些注意事项?保姆级解读
Deep anatomy of C language -- C language keywords
LeetCode:498. 对角线遍历
Generator parameters incoming parameters
企微服务商平台收费接口对接教程
After PCD is converted to ply, it cannot be opened in meshlab, prompting error details: ignored EOF
marathon-envs项目环境配置(强化学习模仿参考动作)
LeetCode:394. 字符串解码
角色动画(Character Animation)的现状与趋势