SwadhyAI Notes

All Python notes

Binary Search Tree (BST) 🔍

Ordered Hierarchy

A BST is a binary tree where the left child contains only nodes with values less than the parent, and the right child only nodes with values greater than the parent.

💻 Implementation

python
class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key

def insert(root, key):
    if root is None:
        return Node(key)
    else:
        if root.val < key:
            root.right = insert(root.right, key)
        else:
            root.left = insert(root.left, key)
    return root

def search(root, key):
    if root is None or root.val == key:
        return root
    if root.val < key:
        return search(root.right, key)
    return search(root.left, key)

🎮 Interactive BST Demo

ℹ️ Ready to build a BST!
Empty BST

⚡ Efficiency

Search, Insert, Delete: O(h) where h is height. Balanced BSTs give O(log n).