Serialize and Deserialize Binary Tree
Thoughts
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
private final String SPLITER = "/";
private final String NULL = "#";
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
if (root == null) {
sb.append(NULL).append(SPLITER);
} else {
sb.append(root.val).append(SPLITER);
sb.append(serialize(root.left));
sb.append(serialize(root.right));
}
return sb.toString();
}
int i = -1;
private TreeNode dfs(String[] subs) {
i++;
if (subs[i].equals(NULL)) {
return null;
}
TreeNode node = new TreeNode(Integer.parseInt(subs[i]));
node.left = dfs(subs);
node.right = dfs(subs);
return node;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] subs = data.split(SPLITER);
return dfs(subs);
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));Analysis
Ver.2
Ver.3
Ver. 4
Last updated