avatar

Catalog
二叉树的序列化与反序列化

解题思路

序列化时,直接使用广度遍历,不用多讲。主要把null也一并保存
反序列化时,同样可以使用队列和广度遍历,每次将节点的左子树和右子树赋值。同时将左子树和右子树进队列。

代码

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root==null){
return "";
}
Queue<TreeNode> que = new LinkedList<TreeNode> ();
que.offer(root);
String res = "";
while(!que.isEmpty()){ // 只要队列不空,一直循环,意味着还没有遍历结束
TreeNode t = que.poll();
if(t==null){
res += "null,";
continue;
}
if(t.left != null){
que.offer(t.left); // 进入队列,这样可以保证先进先出
}else{
que.offer(null);
}
if(t.right!= null){
que.offer(t.right);
}else{
que.offer(null);
}
res += String.valueOf(t.val)+",";
}
return res;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data==null || data.length()==0){
return null;
}
String []s = data.split(",");
int i = 0;
TreeNode t = new TreeNode(Integer.valueOf(s[i++]));
Queue<TreeNode> que = new LinkedList<TreeNode>();
que.offer(t);
while(!que.isEmpty()){
TreeNode n = que.poll();
if(!s[i].equals("null")){
n.left =new TreeNode(Integer.valueOf(s[i++]));
que.offer(n.left);
}else{
i++;
}
if(!s[i].equals ("null")){
n.right =new TreeNode(Integer.valueOf(s[i++]));
que.offer(n.right);
}else{
i++;
}
}
return t;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
Author: kim yhow
Link: http://yoursite.com/2020/06/16/二叉树的序列化与反序列化/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
    微信
  • 支付寶
    支付寶