当前位置:网站首页>[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,
resaccording 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 timestrsTwo 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,
resaccording to,Get by segmentation String Arraystrs, Each position represents the value of a node . Define global variablesind, Used to record the current traversal tostrsThe 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 tostrsThe 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);
}
}
边栏推荐
- CSP first week of question brushing
- Warning in install. packages : package ‘RGtk2’ is not available for this version of R
- Leetcode: Sword Finger offer 42. Somme maximale des sous - tableaux consécutifs
- 优秀的软件测试人员,都具备这些能力
- 自动化测试框架有什么作用?上海专业第三方软件测试公司安利
- PC easy to use essential software (used)
- LeetCode:剑指 Offer 48. 最长不含重复字符的子字符串
- 力扣每日一题(二)
- [embedded] print log using JLINK RTT
- 超高效!Swagger-Yapi的秘密
猜你喜欢

Generator parameters incoming parameters

目标检测——Pytorch 利用mobilenet系列(v1,v2,v3)搭建yolov4目标检测平台

win10系统中的截图,win+prtSc保存位置

LeetCode:221. 最大正方形

可变长参数

深度剖析C语言数据在内存中的存储

Swagger setting field required is mandatory

After PCD is converted to ply, it cannot be opened in meshlab, prompting error details: ignored EOF

Light of domestic games destroyed by cracking

Navicat premium create MySQL create stored procedure
随机推荐
Target detection - pytorch uses mobilenet series (V1, V2, V3) to build yolov4 target detection platform
ESP8266-RTOS物联网开发
Navicat Premium 创建MySql 创建存储过程
View computer devices in LAN
Philosophical enlightenment from single point to distributed
The mysqlbinlog command uses
After PCD is converted to ply, it cannot be opened in meshlab, prompting error details: ignored EOF
如何有效地进行自动化测试?
Super efficient! The secret of swagger Yapi
深度剖析C语言指针
Process of obtaining the electronic version of academic qualifications of xuexin.com
Unsupported operation exception
Using C language to complete a simple calculator (function pointer array and callback function)
【ROS】usb_ Cam camera calibration
opencv+dlib实现给蒙娜丽莎“配”眼镜
同一局域网的手机和电脑相互访问,IIS设置
Tdengine biweekly selection of community issues | phase III
LeetCode:34. 在排序数组中查找元素的第一个和最后一个位置
UML图记忆技巧
Current situation and trend of character animation