Linked lists · Exercise 22 of 100
Turn a search tree into a sorted list
In a binary search tree, visiting the left subtree, the node, then the right subtree gives the values in sorted order. Build the doubly linked list in that order by linking each new entry back to the previous entry and the previous entry forward to it. Those two links let you walk the sorted values in either direction.
Try it yourself
A tree has root 8 with children 3 on the left and 12 on the right. Node 3 has right child 6, and node 12 has left child 10. There are no other nodes. In the sorted doubly linked list, what value do you reach by following two previous links from 10?
One-step hint
Write the tree keys in inorder. Put a finger on 10 and move one place left for each previous link.
Worked solution
- Visit 3 and 6 in the left subtree, then root 8, then 10 and 12 in the right subtree. The forward order is 3, 6, 8, 10, 12.
- The previous link from 10 goes to 8, and the previous link from 8 goes to 6.