Trees and binary search trees · Exercise 37 of 100

Convert a BST to a sorted array

In a binary search tree with distinct keys, each node lies between the values in its left and right subtrees. Append each key to an array during an inorder traversal so the smaller keys are already in the array when their parent is added.

Try it yourself

A BST has root 13 with left child 6 and right child 21. Node 6 has left child 1 and right child 9. Node 21 has only a left child, 17. After conversion to a sorted array, what is the index of 17 if the first index is 0?

One-step hint

Count the keys that appear before 17 in a left-root-right traversal. That count gives its position when indexing starts at zero.

Worked solution
  1. Append 1, 6, and 9 from the left subtree, then append 13. Those four values occupy indices 0 through 3.
  2. In the right subtree, visit 17 before 21 because 17 is its left child. The next free index is 4, so that is where 17 goes.
DSA compiler