/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/publicclassCodec{StringSEP=",";StringNULL="#";// Encodes a tree to a single string.publicStringserialize(TreeNode root){// 二叉树序列化字符串 其实就是先序遍历StringBuilder sb =newStringBuilder();serialize(root,sb);return sb.toString();}voidserialize(TreeNode root,StringBuilder sb){if(root ==null){
sb.append(NULL).append(SEP);return;}// 先序遍历算法
sb.append(root.val).append(SEP);serialize(root.left,sb);serialize(root.right,sb);}// Decodes your encoded data to tree.publicTreeNodedeserialize(String data){// 字符串 转换为列表 LinkedList 是一个双链表 模仿队列 尾部添加元素 头部删除元素LinkedList<String> nodes =newLinkedList<>();for(String s: data.split(SEP)){
nodes.addLast(s);// 尾部添加元素 字符串}returndeserialize(nodes);}TreeNodedeserialize(LinkedList<String> nodes){if(nodes.isEmpty()){returnnull;}// 最左侧就是根节点 头部出队String first = nodes.removeFirst();if(first.equals(NULL)){returnnull;}TreeNode root =newTreeNode(Integer.parseInt(first));
root.left =deserialize(nodes);
root.right =deserialize(nodes);return root;}}// Your Codec object will be instantiated and called as such:// Codec ser = new Codec();// Codec deser = new Codec();// TreeNode ans = deser.deserialize(ser.serialize(root));