Trees and binary search trees · Exercise 33 of 100
Save and rebuild a binary tree
To save a tree in preorder, write each node's value followed by its left and right subtrees, using a marker for each empty link. Choose a marker distinct from every possible value so that missing children can be recognized. To rebuild the tree, read the tokens in order and fill each left child position before its matching right child position.
Try it yourself
A saved tree contains the preorder tokens 8 3 # 6 # # 11 # #, where # marks an empty link. After rebuilding the tree, what value is the right child of 3?
One-step hint
Give node 3 two empty child slots. Read the tokens after 3 in preorder, letting each # fill one slot without creating a node.
Worked solution
- Read 8 as the root and 3 as its left child. The first # fills the empty left link of 3.
- The next open position is the right link of 3. The next token is 6, so its right child has value 6.