Trees and Binary Search Trees

📖 Introduction

Trees are everywhere in software development. File systems, DOM structures, database indexes, decision trees in ML models—understanding trees opened my eyes to how hierarchical data naturally organizes itself.

When I first worked on a project involving expression parsing, trees transformed what seemed like an impossible problem into an elegant recursive solution. The moment tree traversals "clicked" for me was a turning point in my understanding of recursive thinking.


🌳 Tree Fundamentals

A tree is a hierarchical data structure with nodes connected by edges, forming a parent-child relationship.

spinner

Terminology

class TreeNode:
    """Basic tree node."""
    def __init__(self, val):
        self.val = val
        self.children = []

# Terminology:
# - Root: Node with no parent (top of tree)
# - Leaf: Node with no children (bottom of tree)
# - Parent: Node directly above in hierarchy
# - Child: Node directly below in hierarchy
# - Siblings: Nodes sharing same parent
# - Depth: Distance from root (root depth = 0)
# - Height: Distance to furthest leaf
# - Subtree: A node and all its descendants

Binary Tree

Most common tree variant—each node has at most two children.

Types of Binary Trees

spinner

🔄 Tree Traversals

Depth-First Search (DFS)

Three ways to traverse with DFS:

spinner

When to Use Each Traversal

Traversal
Use Case

Preorder

Create copy of tree, prefix expression

Inorder

BST sorted order, expression parsing

Postorder

Delete tree, postfix expression, subtree computations

Breadth-First Search (BFS)

Level by level traversal.


🔍 Binary Search Tree (BST)

A BST maintains the property: left < root < right.

spinner

BST Operations

BST Properties


📊 Common Tree Problems

Maximum Depth

Same Tree / Symmetric Tree

Invert Binary Tree

Path Sum

Lowest Common Ancestor

Diameter of Binary Tree

Balanced Binary Tree

Serialize and Deserialize

Build Tree from Traversals


🌲 Special Tree Types

N-ary Tree

Trie (Prefix Tree)


📝 Practice Exercises

Exercise 1: Right Side View

chevron-rightSolutionhashtag

Exercise 2: Flatten Binary Tree to Linked List

chevron-rightSolutionhashtag

Exercise 3: Maximum Path Sum

chevron-rightSolutionhashtag

🔑 Key Takeaways

  1. Trees are hierarchical structures—think recursively

  2. DFS (preorder, inorder, postorder) uses stack/recursion

  3. BFS uses queue for level-order traversal

  4. BST provides O(log n) operations when balanced

  5. Inorder traversal of BST gives sorted order

  6. Trie is optimal for prefix-based string operations


🚀 What's Next?

In the next article, we'll explore heaps and graphs:

  • Min/max heap operations

  • Priority queue implementation

  • Graph representations

  • Graph traversal algorithms

Next: Article 9 - Heaps & Graphs


📚 References

  • CLRS Chapter 12: Binary Search Trees

  • CLRS Chapter 10: Basic Tree Concepts

  • "Grokking Algorithms" - Trees and Graphs

Last updated