297. 二叉树的序列化与反序列化
难度:困难 2020/6/16每日一题打卡√
题目描述
解题思路
1、层次遍历
先层次遍历得到结果,然后也按照层次遍历的办法把结果重建回来
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int x) {
val = x;
}
}
public class Codec {
// Encodes a tree to a single string.
//层序遍历
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
sb.append('[');
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()) {
int size = queue.size();
while(size-- > 0) {
TreeNode temp = queue.poll();
if(temp != null) {
sb.append(String.valueOf(temp