Insertion

As I mentioned earlier, binary search trees are at their best when it comes to insertion. Now we’ll see why.

Say we want to insert the number 45 into our example tree. The first thing we’d have to do is find the correct node to attach the 45 to. To begin our search, we start at the root:

images/binary_trees/bst_6.png

Since 45 is less than 50, we drill down to the left child:

images/binary_trees/bst_10.png

Since 45 is greater than 25, we must inspect the right child:

images/binary_trees/bst_11.png

Since 45 is greater than 33, we ...

Get A Common-Sense Guide to Data Structures and Algorithms in Python, Volume 1 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.