Binary Search Trees (BST): Insertion, Deletion, and Depth-First Traversals

Master Binary Search Trees with code implementations in Python and JavaScript for In-Order, Pre-Order, and Post-Order algorithms.

Binary Search Trees (BST): Insertion, Deletion, and Depth-First Traversals

A Binary Search Tree (BST) is a hierarchical node-based data structure where each node has at most two children, satisfying the BST Invariant: for any node (X), all keys in its left subtree are strictly less than (X), and all keys in its right subtree are strictly greater than (X).

1. BST Invariant Visualized

        [ 50 ]
        /    
     [ 30 ]  [ 70 ]
     /       /   
   [20] [40] [60] [80]

Left children < Parent < Right children at every subtree level.

2. Python Implementation of Node and BST Class

Here is a complete, production-grade implementation of a Binary Search Tree with recursive insertion, lookup, and in-order traversal:

binary_search_tree.py
class TreeNode:
    def __init__(self, key: int) -> None:
        self.val = key
        self.left = None
        self.right = None

class BinarySearchTree:
    def __init__(self) -> None:
        self.root = None

    def insert(self, key: int) -> None:
        """Public insertion API."""
        if not self.root:
            self.root = TreeNode(key)
        else:
            self._insert_recursive(self.root, key)

    def _insert_recursive(self, current: TreeNode, key: int) -> None:
        if key < current.val:
            if current.left is None:
                current.left = TreeNode(key)
            else:
                self._insert_recursive(current.left, key)
        elif key > current.val:
            if current.right is None:
                current.right = TreeNode(key)
            else:
                self._insert_recursive(current.right, key)

    def inorder_traversal(self) -> list[int]:
        """Returns keys in ascending sorted order."""
        result = []
        def _inorder(node: TreeNode):
            if node:
                _inorder(node.left)
                result.append(node.val)
                _inorder(node.right)
        _inorder(self.root)
        return result

# Verification
bst = BinarySearchTree()
for num in [50, 30, 70, 20, 40, 60, 80]:
    bst.insert(num)

print("In-order sorted output:", bst.inorder_traversal())
# Output: [20, 30, 40, 50, 60, 70, 80]

3. The Three Tree Traversals Compared

Traversal Strategy Order Sequence Primary Use-Case
In-Order (LNR) Left Subtree → Node → Right Subtree Yields elements in sorted monotonic ascending order
Pre-Order (NLR) Node → Left Subtree → Right Subtree Serializing/cloning a tree structure to disk
Post-Order (LRN) Left Subtree → Right Subtree → Node Deleting nodes from leaf to root, evaluating postfix expressions

Discussion (0)

Leave a Thought or Question

No comments posted yet. Be the first to start the discussion!