Save and rebuild a binary tree · Compiler
Save and rebuild a binary tree
Rebuild a binary tree from its preorder encoding, then serialize it in level order. Start a FIFO queue with the root slot. For an empty slot emit #. For an occupied slot emit its value and enqueue its left and right child slots in that order, including missing children. Stop when the queue is empty.
- Input
- Read a single line of space-separated tokens encoding exactly one tree with 0 to 100 nodes. In preorder, # encodes an empty subtree, and an integer value is followed by the encodings of its left and right subtrees. Values are in [-1000, 1000].
- Output
- Print the level-order tokens on one line separated by spaces. Keep all # tokens, including the trailing ones. The empty tree is encoded as a single #.
Compiler Explorer runs your code when you run or check it.
Loading your exercise draft…