Bst In Order Traversal

Sometimes we have a BST and we want to go through the items in order from smallest to largest. This is called an "in-order traversal."

We can write a recursive algorithm for this:

  • Everything in the left subtree is smaller, so print that first, then,
  • print the current node, then
  • print the right subtree.
def inorder_print(node): if node: inorder_print(node.left) print node.value inorder_print(node.right)

This takes time (we're traversing the whole tree, so we're looking at all n items) and space, where h is the height of the tree (this is the max depth of the call stack during our recursion).

If the tree is balanced its height is lg(n), so we have space. If we can't make any assumptions about the "shape" of the tree, in the worst case it's just one continuous line, giving us a height of n, and a space complexity of for our recursive in-order traversal.

What's next?

If you're ready to start applying these concepts to some problems, check out our mock coding interview questions.

They mimic a real interview by offering hints when you're stuck or you're missing an optimization.

Try some questions now

. . .