Design an algorithm to serialize a binary tree to a string and deserialize that string back to the original tree.
Write nodes in BFS order with '#' for null children (the LeetCode format). Decode by handing out children to queued parents two tokens at a time.
1function serialize(root: TreeNode | null): string {2const out: string[] = [], queue = [root];3while (queue.length) {4const n = queue.shift()!;5out.push(n ? String(n.val) : "#");6if (n) queue.push(n.left, n.right);7}8return out.join(",");9}10function deserialize(data: string): TreeNode | null {11const tokens = data.split(",");12if (tokens[0] === "#") return null;13const root = new TreeNode(Number(tokens[0])), queue = [root];14let i = 1;15while (queue.length) {16const n = queue.shift()!;17const l = tokens[i++], r = tokens[i++];18if (l !== "#") queue.push((n.left = new TreeNode(Number(l))));19if (r !== "#") queue.push((n.right = new TreeNode(Number(r))));20}21return root;22}
Write 1; queue its children.
Space: play/pause · ←/→: step