Aan de slagGa gratis aan de slag

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?

Deze oefening maakt deel uit van de cursus

Data Structures and Algorithms in Python

Cursus bekijken

Oefeninstructies

  • 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.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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)
Code bewerken en uitvoeren