Last active
January 28, 2016 12:43
-
-
Save wbars/ddcb8ff30e158d24cda5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Codec { | |
public static class TreeNode { | |
int val; | |
TreeNode left; | |
TreeNode right; | |
TreeNode(int x) { val = x; } | |
} | |
// Encodes a tree to a single string. | |
public String serialize(TreeNode root) { | |
return serialize(root, ""); | |
} | |
public String serialize(TreeNode root, String res) { | |
if (root == null) { | |
return "null"; | |
} | |
res += String.format("%s,%s,%s", Integer.toString(root.val), serialize(root.left, res), serialize(root.right, res)); | |
return res; | |
} | |
// Decodes your encoded data to tree. | |
public TreeNode deserialize(String data) { | |
List<Integer> vals = Arrays.asList(data.split(",")).stream() | |
.map(s -> { | |
if (s.equals("null")) { | |
return null; | |
} else { | |
return Integer.parseInt(s); | |
} | |
}) | |
.collect(Collectors.toList()); | |
return deserialize(vals); | |
} | |
public TreeNode deserialize(List<Integer> data) { | |
if (data.get(0) == null) { | |
data.remove(0); | |
return null; | |
} | |
TreeNode node = new TreeNode(data.remove(0)); | |
node.left = deserialize(data); | |
node.right = deserialize(data); | |
return node; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment