JZ61 序列化二叉树
序列化二叉树
https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84?tpId=13&&tqId=11214&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
java 也有split操作
str.substring(0, str.length() - 1).split(",");
import java.util.*;
//层序遍历
class Solution {
String Serialize(TreeNode root) {
//根节点为空 单独考虑
if(root == null) return "";
Queue<TreeNode> queue2 = new LinkedList<TreeNode>();
queue2.offer(root);
StringBuilder res = new StringBuilder();
while(!queue2.isEmpty()){
TreeNode temp = queue2.poll();
if(temp == null ) res.append("#").append(",");
//这bug不容易查出来 原来后面没加括号
//一定是对流程非常熟悉
else {
res.append(String.valueOf(temp.val)).append(",");
queue2.offer(temp.left);
queue2.offer(temp.right);
}
}
return res.toString();
}
TreeNode Deserialize(String str) {
//根节点为空 单独考虑
if(str.equals("")) return null;
//分割
String[] vals = str.substring(0, str.length() - 1).split(",");
// 根节点加入队列
TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
//根节点的有孩子在 位置 i上
int i = 1;
while(!queue.isEmpty() && i<vals.length) {
TreeNode node = queue.poll();
// 处理右孩子
if(!vals[i].equals("#")) {
node.left = new TreeNode(Integer.parseInt(vals[i]));
queue.add(node.left);
}
i++;
// 处理左孩子
if(!vals[i].equals("#")) {
node.right = new TreeNode(Integer.parseInt(vals[i]));
queue.add(node.right);
}
i++;
}
return root;
}
}