import java.util.*; public class Solution { String Serialize(TreeNode root) { Queue<TreeNode> queue=new LinkedList<>(); StringBuilder result=new StringBuilder(); queue.offer(root); while(!queue.isEmpty()) { /* 这种层序不是完全二叉树,只是将每一层的结点串联起来,不包含空结点 int size=queue.size(); for(int i=0;i<size;i++) { TreeNode node=queue.poll(); result.append(node.val+","); if(node.left!=null) queue.offer(node.left); if(node.right!=null) queue.offer(node.right); } */ //可以在队列中添加null的空结点 TreeNode node=queue.poll(); if(node!=null) { queue.offer(node.left); queue.offer(node.right); result.append(node.val+","); } else { result.append("#"+","); } } if(result.length()!=0) result.deleteCharAt(result.length()-1); return result.toString(); } TreeNode Deserialize(String str) { TreeNode head =null; if(str==null || str.length()==0) return head; String[] nodes=str.split(","); TreeNode[] treenodes=new TreeNode[nodes.length]; for(int i=0;i<nodes.length;i++) { if(!nodes[i].equals("#")) { treenodes[i]=new TreeNode(Integer.valueOf(nodes[i])); } } for(int i=0,j=1;j<treenodes.length;i++) { if(treenodes[i]!=null) { treenodes[i].left=treenodes[j++]; treenodes[i].right=treenodes[j++]; } } return treenodes[0]; } }
原文:https://www.cnblogs.com/lemonzhang/p/13052857.html