Index      Binary Search Tree (BST)  Problems  Change Language   Source

Binary Search Tree (BST)

A Binary Search Tree is a special type of binary tree where the value stored in node u is greater than or equal to all values in its left child's subtree, and greater than or equal to all values in its right child's subtree. A BST allows us to add, delete, or search for a value more efficiently. Searching, insertion, and deletion form the fundamental operations of a BST.

1class Node:
2    def __init__(self, key):
3        self.left = None    # Bache chap
4        self.right = None   # Bache rast
5        self.val = key      # Meghdar

Insertion

The insertion operation for a value x proceeds as follows:

  • First, we examine the root's value. If it is greater than or equal to x, we recursively repeat this step on the left subtree. If smaller, we proceed with the right subtree.

  • We continue until the target child subtree does not exist, then add a new child node with value x in that position.

Deletion

After locating the target node using search, three cases may occur:

  1. Leaf node (no children): Immediate deletion.

  2. Single child: Replace the node with its child.

  3. Two children: Two deletion methods exist. Let u be the node to delete.

Method 1 (Successor replacement): 1. Find node v - the smallest value in u's right subtree. 2. Replace u's value with v's value. 3. Delete v (which can only have 0 or 1 children, as v is the minimum).

Method 2 (Predecessor replacement): - Similar to Method 1, but using the largest value in u's left subtree.