/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/publicclassCodec{// 知識點:String、StringBuilder、parseInt的處理// Encodes a tree to a single string.publicStringserialize(TreeNode root){if(root ==null){return"[]";}StringBuilder res =newStringBuilder("[");Queue<TreeNode> queue =newLinkedList<>();queue.add(root);// 層序遍歷 BFS(迭代) while(!queue.isEmpty()){TreeNode temp = queue.poll();if(temp !=null){// 當前值加入 res,子結點加入 queueres.append(temp.val).append(",");queue.add(temp.left);queue.add(temp.right);}// 空結點 情況else{res.append("null,");}}// 刪除末尾的','res.delete(res.length()-1, res.length());res.append("]");return res.toString();}// Decodes your encoded data to tree.publicTreeNodedeserialize(String data){if(data.equals("[]")){returnnull;}// 1. initString[] vals = data.substring(1, data.length()-1).split(",");TreeNode root =newTreeNode(Integer.parseInt(vals[0]));Queue<TreeNode> queue =newLinkedList<>();queue.add(root);// 2. deserializefor(int i =1;!queue.isEmpty(); i +=2){TreeNode temp = queue.poll();// 左結點判斷if(!vals[i].equals("null")){temp.left =newTreeNode(Integer.parseInt(vals[i]));queue.add(temp.left);}// 右結點判斷if(!vals[i +1].equals("null")){temp.right =newTreeNode(Integer.parseInt(vals[i +1]));queue.add(temp.right);}}return root;}}// Your Codec object will be instantiated and called as such:// Codec codec = new Codec();// codec.deserialize(codec.serialize(root));