AcWing 50. 序列化二叉树
原题链接
困难
作者:
bright
,
2019-07-06 15:06:47
,
所有人可见
,
阅读 820
Java 代码
class Solution {
// Encodes a tree to a single string.
String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node == null) {
sb.append("#,");
}else {
sb.append(node.val + ",");
}
if (node != null) {
queue.offer(node.left);
queue.offer(node.right);
}
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
// Decodes your encoded data to tree.
TreeNode deserialize(String data) {
if (data.length() <= 0)
return null;
String[] strs = data.split(",");
if ("#".equals(strs[0]))
return null;
TreeNode root = new TreeNode(Integer.valueOf(strs[0]));
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int idx = 1;
while (idx < strs.length && !queue.isEmpty()) {
TreeNode work = queue.poll();
if (!"#".equals(strs[idx])) {
work.left = new TreeNode(Integer.valueOf(strs[idx]));
queue.offer(work.left);
}
idx++;
if (!"#".equals(strs[idx])) {
work.right = new TreeNode(Integer.valueOf(strs[idx]));
queue.offer(work.right);
}
idx++;
}
return root;
}
}