题解 | #序列化二叉树#
序列化二叉树
https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
String Serialize(TreeNode root) {
String s = new String();
if(root==null) return s;
Queue<TreeNode> q = new ArrayDeque<>();
q.add(root);
s = s + String.valueOf(root.val) + ' '; // 转换类型
while(!q.isEmpty()){
TreeNode cur=q.poll();
if(cur.left!=null){
s = s + String.valueOf(cur.left.val) + ' ';
q.add(cur.left);
} else{
s = s + 'n' + ' ';
}
if(cur.right!=null){
s = s + String.valueOf(cur.right.val) + ' ';
q.add(cur.right);
} else{
s = s + 'n' + ' ';
}
}
System.out.println(s);
return s;
}
TreeNode Deserialize(String str) {
if(str.isEmpty()) return null;
int i=0;
int cache=0;
Queue<TreeNode> q = new LinkedList<>();
while(str.charAt(i)!=' '){
cache = cache*10 + str.charAt(i++)-'0';
}
i++;
// System.out.println(cache);
TreeNode root = new TreeNode(cache);
q.add(root);
while(!q.isEmpty()){
TreeNode cur = q.poll();
if(i>=str.length()) break;
if(str.charAt(i)=='n'){
cur.left = null;
i++;
}else{
cache = 0;
while(str.charAt(i)!=' '){
cache = cache*10 + str.charAt(i++)-'0';
}
cur.left = new TreeNode(cache);
q.add(cur.left);
}
i++;
if(str.charAt(i)=='n'){
cur.right = null;
i++;
}else{
cache = 0;
while(str.charAt(i)!=' '){
cache = cache*10 + str.charAt(i++)-'0';
}
cur.right = new TreeNode(cache);
q.add(cur.right);
}
i++;
}
return root;
}
}
注意空树的情况。
使用字符'n'表示null,注意单双引号的区别。
还用到了对比版本号的时候用到的字符串转数字的技巧 cache = cache*10 + str.charAt(i++)-'0';
并用了一个while循环和cache变量对分隔开的节点val进行读取。
