解题思路
行序列化,非递归
将非null节点视为有效节点,在size中记录,只将有效节点添加到queue中
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
int size = 0;
Queue queue = new LinkedList<>();
StringBuilder sb = new StringBuilder("[");
if (root != null) {
size++;
queue.offer(root);
}
while (size > 0) {
TreeNode nextNode = queue.poll();
if (nextNode != null) {
// 取出当前节点
size--;
sb.append(nextNode.val).append(",");
/*添加节点*/
// 先考虑当前节点的子节点是否为null
if (nextNode.left != null) {
size++;
}
if (nextNode.right != null) {
size++;
}
// 若当前节点的子节点都为null,且剩余的也都为null
if (size == 0) {
// 则不用添加,直接退出
break;
} else {
queue.offer(nextNode.left);
queue.offer(nextNode.right);
}
} else {
sb.append("null,");
}
}
int len = sb.length();
sb.replace(len - 1, len, "]");
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data.length() < 3) {
return null;
}
String[] subs = data.trim().substring(1, data.length() - 1).split(",");
TreeNode root = new TreeNode(Integer.parseInt(subs[0]));
int length = subs.length;
/*根据树的数学结构 构建*/
// index: 代表了树的构建程度,指向已经构成的最后一个叶子节点的下一位
int index = 1;
Queue queue = new LinkedList<>();
queue.offer(root);
TreeNode temp;
while (true) {
do {
temp = queue.poll();
} while (temp == null);
if (index < length) {
temp.left = "null".equals(subs[index]) ? null
: new TreeNode(Integer.parseInt(subs[index]));
queue.offer(temp.left);
index++; // 每构建一个节点,index++
} else {
break;
}
if (index < length) {
temp.right = "null".equals(subs[index]) ? null
: new TreeNode(Integer.parseInt(subs[index]));
queue.offer(temp.right);
index++; // 每构建一个节点,index++
} else {
break;
}
}
return root;
}
}