/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ publicclassCodec {
privatestaticfinalStringEMPTY="NULL";
// BFS // Encodes a tree to a single string. public String serialize(TreeNode root) { if (root == null) return""; StringBuilderbuilder=newStringBuilder(); Queue<TreeNode> queue = newLinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { TreeNodenode= queue.poll(); if (node == null) builder.append(EMPTY + ","); else { builder.append(node.val).append(","); queue.offer(node.left); queue.offer(node.right); } } return builder.toString(); }
// Decodes your encoded data to tree. public TreeNode deserialize(String data) { if (data == "") returnnull; String[] split = data.split(","); Queue<String> nodes = newLinkedList<>(Arrays.asList(split)); TreeNoderoot=newTreeNode(Integer.parseInt(nodes.poll())); Queue<TreeNode> queue = newLinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { TreeNodenode= queue.poll(); Stringleft= nodes.poll(); Stringright= nodes.poll(); if (!left.equals(EMPTY)) { node.left = newTreeNode(Integer.parseInt(left)); queue.offer(node.left); } if (!right.equals(EMPTY)) { node.right = newTreeNode(Integer.parseInt(right)); queue.offer(node.right); } } 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));
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ publicclassCodec {
privatestaticfinalStringEMPTY="NULL";
// DFS // Encodes a tree to a single string. public String serialize(TreeNode root) { if (root == null) { return EMPTY + ","; } Stringleft= serialize(root.left); Stringright= serialize(root.right); return root.val + "," + left + right; }
// Decodes your encoded data to tree. public TreeNode deserialize(String data) { String[] nodes = data.split(","); Queue<String> queue = newLinkedList<>(Arrays.asList(nodes)); return buildTree(queue); }
// 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));