/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ publicclassCodec {
privatestaticfinalStringNULL="NULL";
privatestaticfinalStringSEPARATOR=",";
// Encodes a tree to a single string. public String serialize(TreeNode root) { StringBuildersb=newStringBuilder(); Queue<TreeNode> queue = newLinkedList<>(); queue.add(root); while (!queue.isEmpty()) { TreeNodenode= queue.poll(); if (node == null) { sb.append(SEPARATOR).append(NULL); } else { sb.append(SEPARATOR).append(node.val); queue.add(node.left); queue.add(node.right); } }
// Decodes your encoded data to tree. public TreeNode deserialize(String data) { String[] strs = data.split(SEPARATOR); if (strs.length == 0 || strs[0].equals(NULL)) { returnnull; }
intindex=1; TreeNoderoot=newTreeNode(Integer.parseInt(strs[0])); Queue<TreeNode> queue = newLinkedList<>(); queue.add(root); while (!queue.isEmpty()) { intcount= queue.size(); for (inti= count; i > 0; i--) { TreeNodecurrent= queue.poll(); if (!strs[index].equals(NULL)) { TreeNodeleft=newTreeNode(Integer.parseInt(strs[index])); current.left = left; queue.add(left); } if (!strs[index + 1].equals(NULL)) { TreeNoderight=newTreeNode(Integer.parseInt(strs[index + 1])); current.right = right; queue.add(right); } index += 2; } } 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));