Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Created August 12, 2017 19:06
Show Gist options
  • Select an option

  • Save cixuuz/3b9dea5218a98f7eb7334d6c4df36562 to your computer and use it in GitHub Desktop.

Select an option

Save cixuuz/3b9dea5218a98f7eb7334d6c4df36562 to your computer and use it in GitHub Desktop.
[297. Serialize and Deserialize Binary Tree] #lc_297
public class Codec {
private static final String SEP = ",";
private static final String NULL = "x";
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
buildString(root, sb);
return sb.toString();
}
private void buildString(TreeNode node, StringBuilder sb) {
if (node == null) {
sb.append(NULL).append(SEP);
} else {
sb.append(node.val).append(SEP);
buildString(node.left, sb);
buildString(node.right, sb);
}
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
Deque<String> values = new LinkedList<>();
values.addAll(Arrays.asList(data.split(SEP)));
return buildTree(values);
}
public TreeNode buildTree(Deque<String> values) {
String val = values.removeFirst();
if (val.equals(NULL)) return null;
TreeNode node = new TreeNode(Integer.parseInt(val));
node.left = buildTree(values);
node.right = buildTree(values);
return node;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment