Pattern visualizer
Serialize and Deserialize Binary Tree
Preorder alone can't be reversed — [1,2,3] is ambiguous about which side 2 and 3 sit on. Writing an explicit '#' for every null child removes the ambiguity: the string tells you exactly when to stop descending, so a single preorder pass can rebuild the tree with no extra traversal needed. Animated on: Design an algorithm to convert a binary tree to a string and back, so the reconstructed tree is identical to the original, for the tree [1, 2, 3, null, null, 4, 5]..
Preorder DFS with a '#' marker for every null child
Call stack
Visit node 1 and append it before recursing into its children (preorder). Output so far: "1".
1FUNCTION serialize(node):2 IF node = NULL: RETURN "#"3 RETURN node.val + "," + serialize(node.left) + "," + serialize(node.right)4END FUNCTION5FUNCTION deserialize(tokens):6 token <- NEXT(tokens)7 IF token = "#": RETURN NULL8 node <- NEW NODE(token)9 node.left <- deserialize(tokens)10 node.right <- deserialize(tokens)11 RETURN node12END FUNCTION
← / → step · space play · Home restart