Binary Search Trees, Graph Traversal (BFS/DFS) & Recursion

10 min read PYTHON 3 views

Binary Search Trees, Graph Traversal (BFS/DFS) & Recursion

Linear data structures like arrays and linked lists organize elements sequentially. However, hierarchical relationships—such as organizational structures, DOM element trees, file systems, and networked social graphs—require non-linear data structures: Trees and Graphs. In this advanced algorithmic lesson, we analyze Binary Search Tree invariants, master recursive divide-and-conquer paradigms, and implement Breadth-First and Depth-First graph traversals.

Binary Search Trees (BST) & The BST Invariant

A binary tree is a hierarchical structure where each parent node possesses at most two children, termed the left and right child. A Binary Search Tree (BST) enforces a fundamental ordering property across all nodes:

  • The value of every node in a node's left subtree is strictly less than the node's own value.
  • The value of every node in a node's right subtree is strictly greater than the node's own value.

When balanced, a BST supports search, insertion, and deletion in O(log n) time. However, if elements are inserted in already-sorted order without balancing, the tree degenerates into a linear linked list with O(n) worst-case performance. Production databases utilize self-balancing search trees (such as Red-Black Trees, AVL Trees, or B-Trees) to guarantee logarithmic bounds.

Tree Traversal Strategies: Inorder, Preorder & Postorder

Depth-first tree traversal visits every node in a binary tree through three canonical ordering sequences:

  1. Inorder (Left, Root, Right): Traverses binary search tree nodes in strictly ascending numerical or alphabetical sorted order.
  2. Preorder (Root, Left, Right): Visits parent nodes before children, ideal for duplicating or serializing tree structures into flat file formats.
  3. Postorder (Left, Right, Root): Visits children before parents, mandatory for bottom-up operations such as deleting trees or calculating directory byte sizes.

Recursion and The Call Stack

Recursion is a programming paradigm where a function solves a problem by calling itself with smaller instances of the same problem. Every recursive algorithm must declare two essential components:

  1. Base Case: A terminating condition that returns a concrete answer without further recursive invocations, preventing infinite recursion and call stack overflow.
  2. Recursive Step: Dividing the computational work and invoking the function on the reduced problem space, advancing toward the base case.

Graph Representations: Adjacency List vs Adjacency Matrix

A graph consists of a set of vertices (nodes) interconnected by edges. Graphs can be directed (one-way edges) or undirected (two-way edges), and weighted or unweighted. Systems software represents graphs using two primary models:

Representation Space Complexity Edge Existence Query Traversing Neighbors Optimal Use Case
Adjacency List O(V + E) O(degree) O(degree) optimal Sparse graphs (e.g., social networks, road maps)
Adjacency Matrix O(V^2) O(1) instant O(V) Dense graphs where edge density approaches V^2

Graph Traversal: Breadth-First Search vs Depth-First Search

Traversing or searching through connected graphs requires systematic visitation algorithms:

  • Breadth-First Search (BFS): Explores the graph layer by layer, visiting all immediate neighbors before advancing to subsequent depth levels. Implemented iteratively using a Queue. BFS guarantees discovering the shortest unweighted path between two nodes.
  • Depth-First Search (DFS): Plunges deep down each branch path until reaching a dead end, backtracking to explore alternative branches. Implemented using Recursion or an explicit Stack. DFS is optimal for topological sorting, cycle detection, and maze solving.

Weighted Graphs & Shortest Path Algorithms

When graph edges carry numerical weights (such as physical distances, network packet latencies, or monetary tolls), simple BFS is insufficient. For non-negative weighted graphs, Dijkstra's Algorithm computes the shortest path from a source vertex to all other vertices in O((V + E) log V) time by leveraging a Min-Heap (Priority Queue) to greedily explore lowest-cost boundaries first. In transportation routing, GPS navigators, and network routing protocols (OSPF), priority-queue graph traversal represents the foundation of spatial computing.

python Example
Run Code
from collections import deque

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

def bfs_traversal(root):
    """Performs Breadth-First Search level-order traversal on a tree."""
    if not root:
        return []
    result = []
    queue = deque([root])
    while queue:
        node = queue.popleft()
        result.append(node.val)
        if node.left:
            queue.append(node.left)
        if node.right:
            queue.append(node.right)
    return result

if __name__ == "__main__":
    root = TreeNode("SystemRoot")
    root.left = TreeNode("AuthService")
    root.right = TreeNode("BillingService")
    root.left.left = TreeNode("OAuthNode")
    print("BFS Level-Order Node Traversal:", bfs_traversal(root))

Related Tutorials