Pre-order with null markers
Time O(n) Space O(n)serialize: pre-order DFS appending each value, or # for null, separated by commas.
deserialize: split into tokens and read them with an index that moves forward: build(node) = token is # ? null : new node, then left = build(), right = build().
root = [1, 2, 3, null, null, 4, 5]text(list)
Step 1/4Visit the root first: write 1.
import java.util.*;
class Solution {
public TreeNode roundTrip(TreeNode root) {
return deserialize(serialize(root));
}
String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
write(root, sb);
return sb.toString();
}
private void write(TreeNode n, StringBuilder sb) {
if (sb.length() > 0) sb.append(',');
if (n == null) { sb.append('#'); return; }
sb.append(n.val);
write(n.left, sb);
write(n.right, sb);
}
private int pos;
TreeNode deserialize(String data) {
String[] tokens = data.split(",");
pos = 0;
return read(tokens);
}
private TreeNode read(String[] tokens) {
String t = tokens[pos++];
if (t.equals("#")) return null;
TreeNode n = new TreeNode(Integer.parseInt(t));
n.left = read(tokens);
n.right = read(tokens);
return n;
}
}Verdict: Each node and each null is written and read once.