Welcome to our deep dive into Binary Search Trees (BST)! This lesson is perfect for both beginners and intermediates. Let's get started!
A Binary Search Tree (BST) is a type of binary tree in which each node has at most two children - the left child and the right child. The tree follows the BST property, which means the key of the left subtree is less than the key of the root, and the key of the right subtree is greater than the key of the root.
Let's create a simple BST and understand how it works!
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.key = key
root = Node(5)
root.left = Node(3)
root.right = Node(7)
root.left.left = Node(2)
root.left.right = Node(4)š” Pro Tip: In this example, we created a simple BST with 5, 3, 7, 2, and 4. The key of the root node (5) is greater than the key of its left child (3) and less than the key of its right child (7).
There are three main operations in a BST:
def insert(root, key):
if root is None:
return Node(key)
else:
if root.key < key:
root.right = insert(root.right, key)
else:
root.left = insert(root.left, key)
return rootš” Pro Tip: In the insert function, we recursively traverse the tree to find the appropriate place for the new node.
def search(root, key):
if root is None or root.key == key:
return root
elif root.key < key:
return search(root.right, key)
else:
return search(root.left, key)š” Pro Tip: In the search function, we traverse the tree recursively until we find the node with the desired key or reach the end of the tree.
Inorder traversal visits the left subtree, then the root, and finally the right subtree. This results in visiting the nodes in sorted order.
def inorder(root):
if root:
inorder(root.left)
print(root.key, end=" ")
inorder(root.right)š” Pro Tip: Inorder traversal is useful for sorting the keys of a BST in ascending order.
What is the key of the right child of the root node in the given BST?
Deleting a node from a BST can be a complex process, but there are several strategies to handle it, such as the Inorder Successor and the Delete with Two Children methods. We'll cover these in a future lesson!
That's it for our Binary Search Trees tutorial! We hope you found it helpful and easy to understand. Happy coding! š