Bitpath

Lesson 2 · Unit 02

Insert and balance

Insertion, and why sorted input ruins the tree

12 exercisesabout 3 min

What you practise

  • Insertion
  • Sorted input degenerates into a list

Try a question from this lesson

Pick one

To insert 5 into this binary search tree, search for it and attach it at the empty spot where the search falls off. Where does 5 end up?

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

The ideas

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

Concept

Insert is search plus attach

Walk down exactly as a search would. The empty spot where you fall off the tree is where the value belongs.

The recursive version returns the root of the subtree it was given, new or old, and the caller re-attaches it. That one habit handles the empty tree too.

def insert(node, x):
    if node is None:
        return Node(x)
    if x < node.val:
        node.left = insert(node.left, x)
    else:
        node.right = insert(node.right, x)
    return node
function insert(node, x) {
  if (node === null) return new Node(x);
  if (x < node.val) {
    node.left = insert(node.left, x);
  } else {
    node.right = insert(node.right, x);
  }
  return node;
}
function insert(
  node: Tree,
  x: number,
): Node {
  if (node === null) return new Node(x);
  if (x < node.val) {
    node.left = insert(node.left, x);
  } else {
    node.right = insert(node.right, x);
  }
  return node;
}

Python noteCall it as root = insert(root, x). Assigning the result back is what makes the very first insert work.

TypeScript noteIt takes a Tree (maybe empty) but returns a Node (never empty): after an insert there is always at least one node. The types record that guarantee.

Concept

Fast only while short

Search and insert cost O(height). With luck, n values fit in about log₂ n levels. Fed sorted input, a plain BST grows n levels and everything becomes O(n).

Self-balancing trees (AVL, red-black) fix this by rotating nodes during insert, keeping the height at O(log n) whatever the order. Databases and sorted maps are built on them.

9 more exercises in the app

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

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