Python Program to Implement a Binary Search Tree
Intermediate · Data structures
A binary search tree (BST) is a tree of nodes where each node has up to two children, every value in its left branch is smaller and every value in its right branch is bigger. That rule makes searching fast, because each comparison rules out a whole branch. This program inserts values, searches for some, and walks the tree in order, which lists the values sorted.
Program
Empty tree in order: [] In-order traversal: [20, 30, 40, 50, 60, 70, 80] Search 60 -> found Search 25 -> not found
How it works
- Each
Nodehas akeyand two links,leftandright, and an empty tree is justroot = None. insert()starts at the root and goes left for a smaller key or right for a bigger one until it reaches an empty spot, where it puts the new node.search()follows the same path, and reachingNonemeans the key is not there, so 25 is reported missing after comparing it with only 50, 30 and 20.in_order()visits the left branch, then the node, then the right branch, which always gives the keys in sorted order.- All three functions are recursive, because the left and right branches are smaller trees that the same function can handle.
Another way to write it
Printing the tree sideways
80
70
60
50
40
30
20Printing the right branch, then the node, then the left branch, with 4 spaces of indent per level, draws the tree on its side: tilt your head to the left and the root, 50, is at the top.
Try it yourself
Add a function that finds the smallest key by following left links until there are none.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises