Binary Tree & BST Serialize & Deserialize
Binary
Binary Tree Serialize with Preorder
public class Codec {
private final static String NULL = "#";
private final static String SEP = ",";
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
serialize(root, sb);
return sb.toString();
}
private void serialize(TreeNode root, StringBuilder sb) {
if (root == null) {
sb.append(NULL).append(SEP);
return;
}
sb.append(root.val).append(SEP);
serialize(root.left, sb);
serialize(root.right, sb);
}
// Decodes your encoded data to tree.
// Or can use an external index
public TreeNode deserialize(String data) {
LinkedList<String> nodeStrList = new LinkedList<>(Arrays.asList(data.split(SEP)));
return deserialize(nodeStrList);
}
private TreeNode deserialize(LinkedList<String> nodeStrList) {
if (nodeStrList.isEmpty()) {
return null;
}
String nodeStr = nodeStrList.removeFirst();
if (nodeStr.equals(NULL)) {
return null;
}
TreeNode node = new TreeNode(Integer.parseInt(nodeStr));
node.left = deserialize(nodeStrList);
node.right = deserialize(nodeStrList);
return node;
}
}BST serializes & deserialize, the difference is that, for BST, the preorder traverse can determine the unique tree, so there is not need to add the "#" to replace the empty nodes
Last updated