Binary Trees and Binary Search Trees: Hierarchical Data

Master tree traversal (inorder, preorder, postorder), BST operations, and when trees outperform other data structures.

published: reading time: 26 min read author: Geek Workbench updated: November 7, 2026
Quick Summary

Binary trees and Binary Search Trees model hierarchical data where each node has at most two children. BST ordering gives path-based O(h) operations, where h is the current height; an ordinary BST can degenerate to height n. AVL and Red-Black trees maintain balance invariants that keep height O(log n). Core traversals include inorder (sorted output), preorder (tree copying), and postorder (tree deletion). Learn when ordered trees suit range queries and iteration better than hash tables.

Binary Trees and Binary Search Trees: Hierarchical Data

Trees model hierarchical relationships where each node can have multiple children but exactly one parent (except the root). Binary trees restrict children to at most two—left and right. This constraint simplifies operations and enables recursive algorithms. Binary Search Trees (BST) add ordering: left descendants < node < right descendants. Search follows one root-to-leaf path, so its cost is O(h), where h is the tree height; a plain BST can reach height n.

Introduction

Trees represent hierarchical data with parent-child relationships and one root. Binary trees limit each node to at most two children, so recursive algorithms can process one subtree at a time. Binary Search Trees (BST) add ordering constraints: left descendants are less than the node, and right descendants are greater. Operations follow a path through the tree and cost O(h); they are logarithmic only when balancing keeps the height O(log n).

Trees are used for file systems, XML documents, database indexes, and compiler syntax trees. AVL and Red-Black trees keep their height logarithmic through insertions and deletions; an ordinary BST has no such guarantee.

This guide covers recursive and iterative inorder, preorder, postorder, and level-order traversal, along with BST search, insertion, and deletion. It also compares AVL and Red-Black trees with hash tables and explains when the ordering and range-query support justify the extra structure.

Binary Tree Node and Basic Operations

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


class BinaryTree:
    def __init__(self, root=None):
        self.root = root

    # Tree traversal methods
    def inorder_traversal(self, root):
        """Left → Root → Right. Returns sorted for BST."""
        result = []
        def traverse(node):
            if not node:
                return
            traverse(node.left)
            result.append(node.val)
            traverse(node.right)
        traverse(root)
        return result

    def preorder_traversal(self, root):
        """Root → Left → Right. Used for copying trees."""
        result = []
        def traverse(node):
            if not node:
                return
            result.append(node.val)
            traverse(node.left)
            traverse(node.right)
        traverse(root)
        return result

    def postorder_traversal(self, root):
        """Left → Right → Root. Used for deleting trees."""
        result = []
        def traverse(node):
            if not node:
                return
            traverse(node.left)
            traverse(node.right)
            result.append(node.val)
        traverse(root)
        return result

    def level_order_traversal(self, root):
        """BFS: Level by level using queue."""
        if not root:
            return []

        result = []
        queue = [root]

        while queue:
            level = []
            next_level = []
            for node in queue:
                level.append(node.val)
                if node.left:
                    next_level.append(node.left)
                if node.right:
                    next_level.append(node.right)
            result.append(level)
            queue = next_level

        return result

    def zigzag_level_order(self, root):
        """Alternate direction each level."""
        if not root:
            return []

        result = []
        queue = [root]
        left_to_right = True

        while queue:
            level = []
            next_level = []
            for node in queue:
                level.append(node.val)
                if node.left:
                    next_level.append(node.left)
                if node.right:
                    next_level.append(node.right)

            if not left_to_right:
                level.reverse()
            result.append(level)

            queue = next_level
            left_to_right = not left_to_right

        return result

Binary Search Tree Implementation

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


class BinarySearchTree:
    def __init__(self):
        self.root = None
        self.size = 0

    def insert(self, val):
        """O(h), where h is height; O(log n) only when balancing keeps h = O(log n)."""
        new_node = BSTNode(val)

        if not self.root:
            self.root = new_node
        else:
            self._insert_recursive(self.root, new_node)

        self.size += 1

    def _insert_recursive(self, node, new_node):
        if new_node.val < node.val:
            if node.left is None:
                node.left = new_node
            else:
                self._insert_recursive(node.left, new_node)
        else:
            if node.right is None:
                node.right = new_node
            else:
                self._insert_recursive(node.right, new_node)

    def search(self, val):
        """O(h) search."""
        node = self.root
        while node:
            if val == node.val:
                return node
            elif val < node.val:
                node = node.left
            else:
                node = node.right
        return None

    def delete(self, val):
        """O(h) deletion with three cases."""
        self.root = self._delete_recursive(self.root, val)
        self.size -= 1

    def _delete_recursive(self, node, val):
        if not node:
            return None

        if val < node.val:
            node.left = self._delete_recursive(node.left, val)
        elif val > node.val:
            node.right = self._delete_recursive(node.right, val)
        else:
            # Node to delete found
            if not node.left:
                return node.right
            if not node.right:
                return node.left

            # Two children: find inorder successor (min of right subtree)
            successor = self._find_min(node.right)
            node.val = successor.val
            node.right = self._delete_recursive(node.right, successor.val)

        return node

    def _find_min(self, node):
        while node.left:
            node = node.left
        return node

    def _find_max(self, node):
        while node.right:
            node = node.right
        return node

    def lower_bound(self, val):
        """Smallest element >= val. O(h)."""
        result = None
        node = self.root
        while node:
            if node.val >= val:
                result = node
                node = node.left
            else:
                node = node.right
        return result

    def upper_bound(self, val):
        """Largest element <= val. O(h)."""
        result = None
        node = self.root
        while node:
            if node.val <= val:
                result = node
                node = node.right
            else:
                node = node.left
        return result

BST Common Problems

def is_valid_bst(root, min_val=float('-inf'), max_val=float('inf')):
    """Check if tree is a valid BST. O(n)."""
    if not root:
        return True

    if root.val <= min_val or root.val >= max_val:
        return False

    return (is_valid_bst(root.left, min_val, root.val) and
            is_valid_bst(root.right, root.val, max_val))


def kth_smallest(root, k):
    """Find kth smallest in BST. O(h + k)."""
    def count_nodes(node):
        if not node:
            return 0
        return 1 + count_nodes(node.left) + count_nodes(node.right)

    left_count = count_nodes(root.left)

    if k <= left_count:
        return kth_smallest(root.left, k)
    elif k == left_count + 1:
        return root.val
    else:
        return kth_smallest(root.right, k - left_count - 1)


def lowest_common_ancestor(root, p, q):
    """LCA in BST. O(h)."""
    while root:
        if p.val < root.val and q.val < root.val:
            root = root.left
        elif p.val > root.val and q.val > root.val:
            root = root.right
        else:
            return root
    return root


def bst_from_preorder(preorder):
    """Construct BST from preorder traversal. O(n)."""
    if not preorder:
        return None

    root = BSTNode(preorder[0])
    stack = [root]

    for i in range(1, len(preorder)):
        node = BSTNode(preorder[i])
        parent = None

        while stack and stack[-1].val < node.val:
            parent = stack.pop()

        if parent:
            parent.right = node
        else:
            stack[-1].left = node

        stack.append(node)

    return root

When to Use BST vs Hash Table

Operation Plain BST AVL / Red-Black BST Hash Table
Search O(h), O(n) worst O(log n) O(1) avg
Insert O(h), O(n) worst O(log n) O(1) avg
Delete O(h), O(n) worst O(log n) O(1) avg
Ordered operations Yes Yes No
Range queries Yes Yes No
Find min/max O(h), O(n) worst O(log n) O(n)
Sorted traversal Yes Yes No
Memory overhead Lower Higher Higher

Plain BST costs depend on its height h, which can be n; AVL and Red-Black trees keep h = O(log n) by restoring their balance invariants after updates. Use ordered trees for range queries and sorted iteration. If you only need repeated minimum or maximum extraction, a heap / priority queue is a better fit. For average-case key lookup without ordering, see hash maps.

Use a BST when you need:

  • Ordered data
  • Range queries (elements between A and B)
  • Nearest neighbor queries
  • Sorted iteration
  • Prefix-based operations (with trie variant)

Tree Traversal Order

graph TD
    A["1: Root"] --> B["2: Left"]
    A --> C["3: Right"]
    B --> D["4: Left's Left"]
    B --> E["5: Left's Right"]
    C --> F["6: Right's Left"]
    C --> G["7: Right's Right"]

For a tree with root 1, left child 2, right child 3:

  • Preorder (root-left-right): 1, 2, 4, 5, 3, 6, 7
  • Inorder (left-root-right): 4, 2, 5, 1, 6, 3, 7
  • Postorder (left-right-root): 4, 5, 2, 6, 7, 3, 1
  • Level order (BFS): 1, 2, 3, 4, 5, 6, 7

Tree Traversal Applications

Traversal Use Case
Inorder (BST) Sorted order, kth smallest/largest
Preorder Copy tree, serialize/deserialize, prefix expression
Postorder Delete tree, compute directories, suffix expression
Level order Shortest path, level-wide processing

How to Visualize Tree Traversals

The key to each traversal is knowing which node gets visited when:

Traversal What to Watch
Preorder Root first, then all left subtree nodes before anything on the right. The phrase “Root → Left → Right” tells you when nodes get visited, not the recursion order.
Inorder Left subtree finishes, then the root, then right. In a BST this gives sorted order. You can see the left spine get exhausted before right children ever appear.
Postorder Left subtree, then right subtree, then root. The root is always last. That’s why postorder works for deletion—you handle children before the parent.
Level order Queue-based BFS instead of recursion. Nodes come out level by level, left to right. This avoids stack overflow on tall trees.

Tracing tip: Sketch the call stack next to your tree. Recursive traversals use stack frames equal to the current path length. A degenerate tree (basically a linked list) needs n stack frames.

Production Failure Scenarios and Mitigations

BST Degenerating to Linked List from Sorted Inserts

Insert values in sorted order (sequential user IDs, timestamp-based keys from a monotonic counter) and a standard BST builds a chain: each new node becomes the right child of the previous one. The height becomes n, so path-based O(h) operations become O(n).

A backend inserting monotonically increasing event sequence numbers into a plain BST can see search cost grow with the event count. Shuffling input may avoid this shape for a particular batch, but it does not give a worst-case guarantee. If input order is uncontrolled, use an AVL or Red-Black tree that restores its balance invariant after each update; see the AVL tree guide.

Many standard library implementations already handle this. Java’s TreeMap and C++’s std::map both use Red-Black Trees. Python’s dict sidesteps the problem with hash-based lookup; see the hash map guide. If you need ordered traversal, the bisect module on sorted lists may outperform a BST for your access patterns.

Stack Overflow from Unbalanced Recursive Traversal

Recursive traversal allocates one stack frame per tree level. On a balanced tree with 1,000 nodes and height around 10, this is fine. On a degenerate tree with 1,000 nodes and height 1,000, you get 1,000 stack frames. Most systems set the stack limit far lower than that.

In Python, the default recursion limit sits around 1,000 frames. A pathological BST hits RecursionError the moment you try to traverse it. The real fix is iterative traversal with an explicit stack or queue instead of recursion. The level_order_traversal in this post does exactly that. Bumping sys.setrecursionlimit works as a short-term workaround, but it papering over the problem rather than solving it.

Two-Child BST Deletion Leaves a Duplicate or Loses a Subtree

When deleting a node with two children, copy the value of its inorder successor (the minimum in its right subtree), then unlink that successor from its original parent. The successor may have a right child: the parent’s link must be updated to that child. Forgetting to unlink it leaves a duplicate key; clearing the link without reconnecting the child loses part of the tree.

Test deletion when the successor is the immediate right child and when it is deeper in the right subtree with a right child of its own. After each deletion, check that inorder traversal is still sorted and contains every expected key exactly once.

Concurrent Updates Break Tree Invariants

Red-Black insertions and deletions change child links and may rotate or recolor nodes. Concurrent unsynchronized updates can overwrite one another, lose nodes, or leave the search-order or balance invariants broken. Serialize updates with a lock, or use an ordered data structure designed for concurrent mutation.

Trade-Off Table

Property Plain BST AVL Red-Black Tree B-Tree / B+ Tree
Search / insert / delete O(h), O(n) worst O(log n) O(log n) O(log n) node visits
Height bound Up to n O(log n) O(log n) O(log n) with fixed fan-out
Update repair None Rotations Rotations/recoloring Splits/merges
Ordered traversal / ranges Yes Yes Yes Yes
Typical fit Simple ordered data Lookup-heavy ordered data General ordered map Database and file indexes
Locality Shape-dependent Pointer-based Pointer-based Good page locality

Complexity depends on both the operation and the invariant the structure maintains. A plain BST maintains key ordering but no height bound, so search, insert, and delete follow a path of length h and can take O(n). An AVL tree keeps each node’s child-subtree heights within one. A Red-Black tree colors every node red or black, keeps its root and NIL leaves black, disallows red parent-child pairs, and gives every root-to-leaf path equal black height. Each restores its balance rules after updates, keeping height O(log n) and those operations logarithmic. B-trees maintain occupancy and separator-key ordering, keeping height logarithmic in the number of keys while grouping keys into pages. See the AVL rotation guide and B-tree index guide for those invariants.

Security Notes

If untrusted input controls insertion order in a plain BST, crafted keys can produce height n, making lookups and updates O(n); recursive traversals can also consume O(n) stack. Use an AVL or Red-Black tree when a worst-case height bound matters, and use iterative traversal when input can create deep trees. Shuffling only changes expected shape under assumptions; it does not provide the same worst-case guarantee.

When users can add nodes, enforce per-user or per-operation node and memory limits so a valid but very large tree cannot exhaust the process.

Quick Recap Checklist

  • Binary tree: each node has at most 2 children
  • Plain BST: left < root < right gives O(h) path operations; h can be n
  • Inorder traversal of BST gives sorted sequence
  • Deletion has 3 cases: leaf, one child, two children (use successor)
  • Path operations cost O(h); a degenerate tree can have h = n
  • AVL and Red-Black trees restore balance invariants to keep height O(log n)

Interview Questions

1. How do you handle deletion in a BST when the node has two children?

When a node has two children, replace it with its inorder successor (smallest node in right subtree) or inorder predecessor (largest node in left subtree). The successor has at most one child (it can't have a left child by definition—it's the minimum of the right subtree). Copy the successor's value into the node being deleted, then recursively delete the successor. This maintains BST property while keeping deletion O(h).

2. What's the difference between preorder, inorder, and postorder traversal?

The order refers to when the root is visited relative to its children. Preorder: root → left → right (good for copying trees, prefix expressions). Inorder: left → root → right (gives sorted order for BSTs). Postorder: left → right → root (good for deleting trees, computing directory sizes). All three are O(n) with O(h) space for recursion stack.

3. Why can BST operations degrade to O(n)?

If you insert elements in sorted order (1, 2, 3, 4, 5), the BST becomes a degenerate tree (essentially a linked list with no branching). Search, insert, and delete may follow a path of length n → O(n). Use AVL or Red-Black trees when you need a worst-case O(log n) height bound; each restores its balance invariants after updates. Shuffling insertion order can improve the expected shape for a batch, but gives no worst-case guarantee.

4. How do you find the LCA in a BST efficiently?

For a BST, the LCA is the first node whose value lies between the two target values (inclusive). Starting from root, if both p and q are smaller than current node, go left. If both are larger, go right. Otherwise, current node is the LCA (one is in left subtree, one is in right). This is O(h) time and O(1) space. For generic binary trees (not BST), you'd need to find paths from root to both nodes first, then compare where they diverge.

5. What is the time complexity of searching, inserting, and deleting in a BST?

Search, insert, and delete each follow a path and cost O(h), where h is the current height. They are O(log n) only when the structure keeps h = O(log n), as AVL and Red-Black trees do by restoring their balance invariants after each update.

In a plain BST, sorted insertions can make the height n, so operations take O(n). AVL and Red-Black trees keep height O(log n) when their balancing rules are restored after each insertion or deletion.

6. How do you validate whether a binary tree is a valid BST?

Use a recursive approach that passes down allowed min/max bounds. For each node:

  • Check that its value lies in the valid range (min, max)
  • Recurse left with updated max = node.val
  • Recurse right with updated min = node.val

Initialize with min = -∞, max = +∞. An inorder traversal that yields strictly increasing values also confirms BST validity. The bound approach is O(n) with O(h) space.

7. How do you find the kth smallest element in a BST?

Use inorder traversal — since inorder of a BST produces sorted order, the kth element visited is the kth smallest. Two approaches:

  • Recursive with counter: traverse inorder, decrement k on each visit, return when k reaches 0. O(n) time, O(h) space.
  • Augmented BST: store subtree sizes in each node, then compare k with left subtree size to determine which branch to explore. O(h) time.
8. How do you perform a range query in a BST (find all keys between A and B)?

Use a modified inorder traversal that prunes subtrees outside the range:

  • If current node.val > A, recurse left (values smaller than current may still be in range)
  • If A ≤ node.val ≤ B, record the value
  • If current node.val < B, recurse right (values larger than current may still be in range)

This visits only nodes within the range plus a path to the range boundaries — O(m + h) where m is the number of nodes in range. This is a key advantage of BSTs over hash tables, which require scanning all entries.

9. What are self-balancing trees and why are they important?

AVL and Red-Black trees maintain height O(log n) by restoring their balance invariants after insertions and deletions. A plain BST only maintains key ordering and can degenerate into a linked list, making operations O(n).

AVL trees maintain a per-node height difference of at most one; Red-Black trees maintain coloring and black-height rules. Both keep height O(log n). B-Trees and B+ Trees maintain page occupancy through splits and merges, which suits disk-based indexes.

10. How does level-order traversal work and what are its use cases?

Level-order traversal (BFS) visits nodes level by level, left to right within each level. It uses a queue instead of recursion:

  • Enqueue the root node
  • While queue is not empty: dequeue a node, process it, enqueue its left and right children
  • Processing nodes from a single dequeue step yields one level at a time

Use cases include: finding shortest paths in unweighted trees, serializing trees for transmission, printing trees level-by-level, and avoiding stack overflow on deep trees.

11. Explain Morris traversal for O(1) space inorder traversal.

Morris traversal performs inorder traversal using O(1) extra space by temporarily threading leaf nodes back to their successors. The algorithm:

  • Start at root. For each node: if it has no left child, visit it and move to its right child.
  • If it has a left child, find its inorder predecessor (rightmost node in left subtree).
  • If the predecessor's right pointer is null, set it to the current node (create thread), then move to left child.
  • If the predecessor's right pointer already points to current node (thread found), restore it to null, visit current node, then move to right child.

The trade-off is temporary structural modification — the tree is restored to its original shape by the end. Time complexity remains O(n), but each edge is traversed at most twice.

12. What is the difference between AVL trees and Red-Black trees?

AVL trees keep the child-subtree heights at each node within one. Red-Black trees use color and black-height rules to bound their height by O(log n). Both provide logarithmic worst-case search, insert, and delete when each update restores the required invariants.

  • Balance rule: AVL bounds the child-height difference; Red-Black maintains color and black-height constraints.
  • Operations: Both provide O(log n) worst-case search, insert, and delete when updates restore their invariants.
  • Storage: AVL nodes store height or balance information; Red-Black nodes store a color.
  • Choice: Their update and lookup trade-offs depend on the workload and implementation; neither is always faster.
13. How do you find the height of a binary tree?

The height of a binary tree is the length of the longest path from root to a leaf (number of edges). Recursive definition:

  • Base case: empty node has height -1 (or 0 if counting nodes)
  • Recursive: height(node) = 1 + max(height(node.left), height(node.right))

This is O(n) time and O(h) space (recursion stack). An iterative level-order traversal can also compute height by counting the number of BFS levels. Height is the single most important metric for BST performance — it directly determines time complexity.

14. What is the diameter of a binary tree and how do you compute it?

The diameter (or width) is the longest path between any two nodes in the tree, measured by the number of edges along the path. The path does not need to pass through the root.

To compute it efficiently in O(n):

  • For each node, compute the height of its left and right subtrees
  • The diameter passing through that node = left_height + right_height (if counting edges) or left_height + right_height + 2
  • Track the maximum diameter seen across all nodes
  • Return the node's height (1 + max(left, right)) to the parent

This is a classic example of computing two related things (height and diameter) in a single traversal using a helper function.

15. How would you implement an inorder BST iterator?

Implement a class with hasNext() and next() that returns elements in sorted order without using extra memory for all nodes. Use an explicit stack:

  • Constructor: push all left children of the root onto a stack (go down the left spine)
  • next(): pop the top node, return its value. Then push all left children of its right child onto the stack.
  • hasNext(): check if stack is non-empty

This is O(h) space (stack depth equals tree height) and O(1) amortized time per next() call. Each node is pushed and popped exactly once. The iterator pattern is essential for streaming large BSTs without loading all elements into memory.

16. How do you serialize and deserialize a BST?

Serialize: Use preorder traversal to encode the tree structure. Preorder is preferred because the root comes first, enabling recursive reconstruction. Write node values separated by markers (e.g., commas). Represent null children with a sentinel like '#' or 'null'.

Deserialize: Read values in order. Use the preorder property — first value is root, then recursively build left subtree from values smaller than root and right subtree from values larger. Alternatively, for generic binary trees (not BST), use a queue-based approach with null markers.

For BST specifically, you can avoid null markers by using the value bounds (min/max) during deserialization since the ordering property tells you which branch each value belongs to. This is O(n) time and O(n) space.

17. What is a treap and how does it combine BST properties with heap properties?

A treap is a randomized BST where each node gets a random priority treated as a max-heap value. This gives two invariant properties at once: the BST order (left < node < right) and the heap order (node.priority > children's priorities). No complex rotation logic needed.

With independent random priorities, a treap has expected height O(log n), though its worst-case height is still n. On insert, you do a normal BST insert then rotate up to restore heap property. On delete, if the node has two children you rotate it down to a leaf, then remove it. The catch: the tree shape changes each run with the same data, and you spend an extra field per node on the priority. Treaps are easier to implement than Red-Black trees and hold up well in practice.

18. How does inserting N nodes from a sorted array affect a BST, and what is the optimal approach?

Inserting sorted data into a standard BST builds a degenerate tree — essentially a linked list — in O(n²) total time. Each new element walks the entire existing tree before landing at the rightmost position. This is the worst-case scenario for BSTs.

The optimal approach builds the tree in O(n) instead. Pick the array's middle element as the root, then recursively build left and right subtrees from the left and right halves. You always split at the median, which guarantees balance. For sorted data you need to store in a BST, this beats repeated inserts by a mile. If data arrives as a stream, AVL or Red-Black trees provide a worst-case O(log n) height; treaps provide expected O(log n) height with independent random priorities.

19. What is a threaded binary tree and how does it improve traversal efficiency?

A threaded binary tree fills in the null left and right child pointers with links to the inorder predecessor and successor. In a regular binary tree, those null pointers sit there doing nothing — traversal has to backtrack or use a stack. Threading converts them into navigation links.

Single-threaded variants use only right null pointers to link to the inorder successor. Double-threaded uses both null pointers. The payoff is traversal without recursion or a stack — you just follow threads until you hit a dead end. The cost: you need a flag per node to mark which pointers are threads and which are real children, and insert/delete become more fragile since you have to maintain the threads correctly.

20. How would you augment a BST to support order statistics — finding the kth smallest element in O(log n)?

In a balanced augmented BST, store a subtree size in every node: size = 1 + size(left) + size(right). Find the kth smallest by walking down the tree: if k is the left subtree size plus one, you are at the target. If k is smaller, go left; if larger, subtract (left_size + 1) and go right. This takes O(log n) only while the tree keeps height O(log n).

Every insert and delete must maintain sizes along the search path, costing O(h) extra work (O(log n) when the tree stays balanced). This is the order-statistic tree idea. Fenwick trees and segment trees solve the same problem for static arrays, but the BST approach handles dynamic data where elements can be inserted and deleted.

Further Reading

Books and Courses

  • Introduction to Algorithms (CLRS) — Chapters 10, 12, and 13 cover binary trees, BSTs, and Red-Black Trees in depth with formal proofs and exercises.
  • The Algorithm Design Manual (Skiena) — Chapter 3 provides practical advice on tree data structures with real-world war stories.
  • MIT 6.006 Introduction to Algorithms — Lectures on binary trees, BST operations, and AVL trees available free on MIT OpenCourseWare.

Deeper Dives

  • Self-Balancing Trees: Compare AVL and Red-Black balance invariants, then choose based on the workload and implementation. Explore B-Trees and B+ Trees to understand how databases organize indexes.
  • Tree Traversal Variations: Morris traversal achieves inorder traversal in O(1) space by threading leaf pointers. Iterative traversal with explicit stacks eliminates recursion-depth issues. Understand the trade-off between space and complexity.
  • Trie and Radix Trees: When your keys are strings, tries offer prefix-based search in O(k) where k is the key length. Radix trees (PATRICIA) compress common prefixes for memory efficiency — widely used in IP routing tables and autocomplete systems.
  • Segment Trees and Fenwick Trees: For range queries on arrays, segment trees provide O(log n) query and update. Fenwick trees (BIT) are more memory-efficient for prefix sum operations.

Online Resources

  • Visualgo.net — Interactive BST, AVL, and Red-Black tree visualizations with step-by-step execution.
  • LeetCode Tree Tag — Curated problems from easy to hard, covering all traversal types and BST-specific challenges.
  • USACO Guide — Trees — Competitive programming tree problems with editorial solutions.

Conclusion

Binary trees organize hierarchical data with at most two children per node. Binary Search Trees add ordering—left subtree values < node value < right subtree values—so search, insert, and delete follow a path of length h and cost O(h); a plain BST can reach h = n. The four traversal orders each serve different purposes: inorder gives sorted sequence for BSTs; preorder copies trees; postorder deletes trees; level order does BFS. Deletion with two children uses the inorder successor (minimum of right subtree). AVL and Red-Black trees maintain balance invariants that keep height O(log n), while a plain BST can degenerate on sorted inserts. Choose ordered trees for range queries and sorted iteration, or a hash map for unordered key lookup.

Category

Related Posts

AVL Trees: A Hands-On Guide to Rotations

Learn AVL insertions and deletions through height and balance-factor traces, then use a compact Python implementation and compare tree choices.

#avl-tree #self-balancing-bst #binary-search-tree

Red-Black Trees: Balanced Search Trees with Simpler Rotations

Master red-black tree properties, insertion fixup cases, and color flip mechanics. Learn when RB trees outperform AVL and when they don't.

#red-black-tree #self-balancing-bst #binary-search-tree

Arrays vs Linked Lists: Understanding the Trade-offs

Compare arrays and linked lists by access, edits, memory use, and cache behavior, with one operation matrix and a reproducible benchmark for real workloads.

#arrays #linked-lists #data-structures