class TreeNode { val: number; left: TreeNode | null; right: TreeNode | null; constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { this.val = val === undefined ? 0 : val; this.left = left === undefined ? null : left; this.right = right === undefined ? null : right; } } function serialize(root: TreeNode | null): string { if (!root) return 'null'; return root.val + ',' + serialize(root.left) + ',' + serialize(root.right); } const tree = new TreeNode(1, new TreeNode(2), new TreeNode(3, new TreeNode(4), new TreeNode(5))); console.log(serialize(tree));
The serialization uses preorder traversal. For each node, it records the value, then recursively serializes the left and right children. Null children are represented as 'null'. The output string is a comma-separated list of values and 'null's.
class TreeNode { val: number; left: TreeNode | null; right: TreeNode | null; constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { this.val = val === undefined ? 0 : val; this.left = left === undefined ? null : left; this.right = right === undefined ? null : right; } } function deserialize(data: string): TreeNode | null { const list = data.split(','); function helper(): TreeNode | null { if (list.length === 0) return null; const val = list.shift(); if (val === 'null') return null; const node = new TreeNode(Number(val)); node.left = helper(); node.right = helper(); return node; } return helper(); } const root = deserialize("1,2,null,null,3,4,null,null,5,null,null"); console.log(root?.right?.left?.val);
The deserialization reconstructs the tree in preorder. The root's right child is 3, and its left child is 4, so the output is 4.
function serialize(root: TreeNode | null): string {
if (!root) return '';
return root.val + ',' + serialize(root.left) + ',' + serialize(root.right);
}
const tree = new TreeNode(1, new TreeNode(2), null);
console.log(serialize(tree));The code returns an empty string for null nodes instead of 'null'. This causes missing markers for empty nodes and extra commas in the output string, which can cause problems during deserialization.
function deserialize(data: string): TreeNode | null {
const list = data.split(',');
function helper(): TreeNode | null {
if (list.length === 0) return null;
const val = list.shift();
if (val === 'null') return null;
const node = new TreeNode(Number(val));
node.left = helper();
node.right = helper();
return node;
}
return helper();
}
const root = deserialize("1,2,null,null,3,null,4,null,null");The tree has nodes with values 1, 2, 3, and 4. Nulls mark missing children. So total nodes are 4.
Null markers are needed to know where children are missing, so the tree can be rebuilt exactly as it was. Without them, the structure is lost.