serialization
public void serialization (List<String> result, TreeNode node) {
if (node == null) {
result.add("#");
return;
}
result.add(String.valueOf(node.val));
serialization(result, node.left);
serialization(result, node.right);
}
deserialization
public class DeserializeBST {
static String string;
public static void helper(String str, TreeNode root, boolean isLeft) {
if (string.isEmpty()) {
return;
}
if (string.charAt(0) == '#') {
string = string.substring(1);
return;
}
TreeNode newNode = new TreeNode(Integer.parseInt(string.substring(0, 1)));
if(isLeft) {
root.left = newNode;
} else {
root.right = newNode;
}
string = string.substring(1);
helper(string, newNode, true);
helper(string, newNode, false);
}
public static TreeNode deserialize(String str) {
if (str.charAt(0) == '#') {
return null;
}
TreeNode parent = new TreeNode(Integer.parseInt(string.substring(0,1)));
string = string.substring(1);
helper(string, parent, true);
helper(string, parent, false);
return parent;
}
}