Bitpath

Lesson 1 · Unit 02

The ordering rule

Search in O(height), and in-order comes out sorted

11 exercisesabout 3 min

What you practise

  • Search in O(height)
  • In-order visits in sorted order

Try a question from this lesson

Pick one

Every node here has smaller values to its left and larger ones to its right. A search for 6 starts at 8 and compares its way down. Which nodes does it visit?

#       8
#      / \
#     3   10
#    / \    \
#   1   6    14
//       8
//      / \
//     3   10
//    / \    \
//   1   6    14
//       8
//      / \
//     3   10
//    / \    \
//   1   6    14

The idea

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

The BST promise

A binary search tree keeps one promise at every node: everything in the left subtree is smaller, everything in the right subtree is larger.

So a search follows a single path down from the root. Its cost is the height of the tree, not the number of nodes.

def search(node, x):
    while node:
        if x == node.val:
            return True
        if x < node.val:
            node = node.left
        else:
            node = node.right
    return False
function search(node, x) {
  while (node) {
    if (x === node.val) return true;
    if (x < node.val) node = node.left;
    else node = node.right;
  }
  return false;
}
function search(node: Tree, x: number) {
  while (node) {
    if (x === node.val) return true;
    if (x < node.val) node = node.left;
    else node = node.right;
  }
  return false;
}

Python notewhile node: stops at None, the empty link. The loop needs no recursion and no extra memory.

TypeScript notewhile (node) narrows node from Tree to Node inside the loop, so node.val needs no extra check. The return type is inferred as boolean.

9 more exercises in the app

  • 3× type the answer
  • 1× fill the blanks
  • 1× true or false
  • 2× multiple choice
  • 1× order the lines
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy