Get startedGet started for free

Printing book titles in alphabetical order

This video taught you three ways of implementing the depth first search traversal into binary trees: in-order, pre-order, and post-order.

In the following binary search tree, you have stored the titles of some books.

Graphical representation of a binary search tree.

The tree has been preloaded in the bst variable (line 15):

bst = CreateTree()

Can you apply the in-order traversal so that the titles of the books appear alphabetically ordered?

This exercise is part of the course

Data Structures and Algorithms in Python

View Course

Exercise instructions

  • Check if current_node exists.
  • Call the in_order() function recursively on the appropriate half of the tree.
  • Print the value of the current_node.
  • Call the in_order() function recursively on the other half of the tree.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

class BinarySearchTree:
  def __init__(self):
    self.root = None

  def in_order(self, current_node):
    # Check if current_node exists
    if ____:
      # Call recursively with the appropriate half of the tree
      self.in_order(current_node.____)
      # Print the value of the current_node
      print(____)
      # Call recursively with the appropriate half of the tree
      self.in_order(current_node.____)
  
bst = CreateTree()
bst.in_order(bst.root)
Edit and Run Code