diff --git a/Hard/SerializeandDeserializeBinaryTree.java b/Hard/SerializeandDeserializeBinaryTree.java new file mode 100644 index 0000000..8a467ea --- /dev/null +++ b/Hard/SerializeandDeserializeBinaryTree.java @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Codec { + + // Encodes a tree to a single string. + public String serialize(TreeNode root) { + if(root == null){ + return "X"; + } + String leftSerialized = serialize(root.left); + String rightSerialized = serialize(root.right); + return root.val + ","+leftSerialized + ","+rightSerialized; + } + + // Decodes your encoded data to tree. + public TreeNode deserialize(String data) { + Queue nodesLeft = new LinkedList<>(); + nodesLeft.addAll(Arrays.asList(data.split(","))); + return deserializeHelper(nodesLeft); + + } + public TreeNode deserializeHelper(Queue nodesLeft){ + String valueforNode = nodesLeft.poll(); + if(valueforNode.equals("X")) return null; + TreeNode newNode = new TreeNode(Integer.valueOf(valueforNode)); + newNode.left = deserializeHelper(nodesLeft); + newNode.right = deserializeHelper(nodesLeft); + return newNode; + } +} \ No newline at end of file