https://leetcode-cn.com/problems/xu-lie-hua-er-cha-shu-lcof/
就是层级遍历,搞一个queue,然后层级遍历,左右子树为空也要add到queue,因为要保留整颗树的结构,反解析的时候同理,遇到为null的,就不添加queue了
import java.util.LinkedList; import java.util.Queue; public class Codec { public String serialize(TreeNode root) { if(root == null) { return "[]" ; } StringBuilder stringBuilder = new StringBuilder(); Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); stringBuilder.append("["); while (!queue.isEmpty()){ TreeNode node = queue.poll(); if(node != null) { stringBuilder.append(node.val); stringBuilder.append(","); queue.add(node.left); queue.add(node.right); } else { stringBuilder.append("null,"); } } stringBuilder.deleteCharAt(stringBuilder.length()-1); stringBuilder.append("]"); return stringBuilder.toString(); } public TreeNode deserialize(String data) { if(data.equals("[]")) { return null; } String nodeStr = data.substring(1, data.length()-1); String[] nodeVal = nodeStr.split(","); TreeNode root = new TreeNode(Integer.parseInt(nodeVal[0])); Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); int index = 1; while (!queue.isEmpty()){ TreeNode node = queue.poll(); if(!nodeVal[index].equals("null")){ node.left = new TreeNode(Integer.parseInt(nodeVal[index])); queue.add(node.left); } index++; if(!nodeVal[index].equals("null")){ node.right = new TreeNode(Integer.parseInt(nodeVal[index])); queue.add(node.right); } index++; } return root; } }