/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/publicclassCodec{// Encodes a tree to a single string.publicStringserialize(TreeNoderoot){returndoSerialize(root,"");}privateStringdoSerialize(TreeNoderoot,Stringstr){if(root==null){str+="N,";returnstr;}str+=root.val+",";str=doSerialize(root.left,str);str=doSerialize(root.right,str);returnstr;}// Decodes your encoded data to tree.publicTreeNodedeserialize(Stringdata){String[]strs=data.split(",");returndoDeserialize(newLinkedList<>(Arrays.asList(strs)));}privateTreeNodedoDeserialize(List<String>nodes){if("N".equals(nodes.get(0))){nodes.remove(0);returnnull;}TreeNoderoot=newTreeNode(Integer.parseInt(nodes.get(0)));nodes.remove(0);root.left=doDeserialize(nodes);root.right=doDeserialize(nodes);returnroot;}}// Your Codec object will be instantiated and called as such:// Codec ser = new Codec();// Codec deser = new Codec();//TreeNodeans=deser.deserialize(ser.serialize(root));
classCodec{staticTreeNodet;// Encodes a tree to a single string.publicStringserialize(TreeNoderoot){t=root;return"";}// Decodes your encoded data to tree.publicTreeNodedeserialize(Stringdata){returnt;}}