All examples

Examples

Building a binary search tree in C++

Seven keys inserted one by one: each comparison sends a key left or right down the tree, beside the recursive C++ insert and its call stack.

This video was made with the Algorithm visuals skill.

  • 1:00
  • Algorithm visuals
  • Narrated by Sulafat
  • English

Made from a prompt

Insert 50, 30, 70, 20, 40, 60, 80 into a binary search tree, in C++

Video transcript

How do you add keys while keeping a binary search tree ordered?

The code inserts these 7 keys. Smaller keys go left; others go right. Orange marks execution; green marks completed nodes.

Line 7 finds nullptr, so line 8 creates the root, 50.

30 is smaller than 50, so recursion goes left and creates 30.

70 is greater than 50, so it becomes the right child.

20 goes left of 30; 40 goes right of 30. Then 60 passes right of 50 and goes left of 70.

80 reaches 50. Which way will you go?

80 exceeds 50 and 70, so 80 becomes 70's right child.

The smaller-left, others-right rule holds. Comparisons guide insertion, but a skewed tree makes each insertion linear.

Your topic, drawn in about a minute.

Your first 2 videos are free, up to 1 minute each, watermarked. No card required. Full product, every voice and style included.