Trees and Balanced Search Structures · Balanced Trees

B Tree

B trees store multiple keys per node and keep height small, making them important for database and file-system indexing.

Student Focus

We teach B trees as a practical indexing idea, not just an abstract tree variant.

Guided Lesson Notes

Understanding B Tree

B Tree focuses on hierarchical relationships, recursive subproblems, and shape rules that control performance. B trees store multiple keys per node and keep height small, making them important for database and file-system indexing.

The mental model is this: draw nodes as parent-child relationships; every node is the root of a smaller tree with the same rules. That picture matters because it tells the student what information is available immediately and what must be searched, stored, or recomputed.

The core invariant is that the shape or ordering rule must hold at every node, not just near the root. If a solution cannot state that rule, the code may still run on a sample input but fail on edge cases.

A strong implementation usually uses recursive traversal, iterative queues for levels, search paths, rotations, splits, merges, or range-query recursion. The goal is not just to memorize an API; the goal is to know why each operation is allowed and what it costs.

In competitive programming, B Tree tends to appear when the problem describes hierarchy, ancestry, subtrees, intervals, prefixes, sorted dynamic data, or range queries. Spotting that signal is often the difference between a nested-loop solution and an efficient one.

Visual Model

A small picture for B Tree

rootLRABCD

Key Ideas

  • Multi-key nodes
  • Minimum and maximum children
  • Disk-friendly branching

Practice Prompts

  • Insert values into a small B tree by hand.
  • Explain why high branching factor reduces tree height.

Vocabulary

Terms students should be able to say clearly

Root

The top node where tree reasoning begins.

Leaf

A node with no children.

Height

The length of the longest downward path from a node.

Subtree

A node together with all descendants below it.

Traversal

A systematic order for visiting nodes.

Balance

A shape condition that keeps paths from becoming too long.

Worked Example

Worked example: tracing B Tree

Use a tiny input and focus on multi-key nodes. The goal is to see how the topic changes state before scaling it to a full problem.

  1. 1Write a small input where B Tree is clearly useful.
  2. 2Label the part of the input related to Multi-key nodes.
  3. 3Perform one operation and explain which invariant is still true afterward.
  4. 4Run a second operation that touches an edge case, such as an empty side, duplicate value, boundary index, disconnected vertex, or tie.
  5. 5Finish by saying which operation dominates the runtime and why.

Complexity Check

Costs students should be able to explain

OperationTypical CostReason
TraversalO(n)Visiting every node takes time proportional to the number of nodes.
Balanced searchO(log n)Balanced height keeps search paths short.
Unbalanced searchO(n)A poor shape can behave like a linked list.

Common Mistakes

What to watch while practicing

  • Coding before drawing the structure or state changes.
  • Forgetting the invariant that makes the algorithm correct.
  • Testing only the sample input and skipping boundary cases.
  • Giving Big-O without explaining which operation dominates the work.

Interview-Style Coding Problem

B Tree interview problem: Diameter of a Tree

Interview medium

Problem

Given an undirected tree, find the number of edges on the longest path between any two nodes.

Input

The first line contains n. The next n - 1 lines contain edges u v using 1-based node labels.

Output

Print the tree diameter in edges.

Sample Input

6
1 2
2 3
2 4
4 5
5 6

Sample Output

4

Why the sample works

One longest path is 3-2-4-5-6, which uses four edges.

Approach

  1. 1Run BFS from any node to find a farthest endpoint.
  2. 2Run BFS again from that endpoint.
  3. 3The largest distance in the second BFS is the diameter.
  4. 4This works because a farthest node from any start is an endpoint of a longest path.

O(n) time and O(n) extra space.

Java Solution

import java.util.*;

public class Main {
  static int[] bfs(List<Integer>[] graph, int start) {
    int n = graph.length - 1;
    int[] dist = new int[n + 1];
    Arrays.fill(dist, -1);

    Queue<Integer> q = new ArrayDeque<>();
    q.add(start);
    dist[start] = 0;

    while (!q.isEmpty()) {
      int node = q.remove();
      for (int next : graph[node]) {
        if (dist[next] == -1) {
          dist[next] = dist[node] + 1;
          q.add(next);
        }
      }
    }

    int farthest = start;
    for (int i = 1; i <= n; i++) {
      if (dist[i] > dist[farthest]) farthest = i;
    }

    return new int[] {farthest, dist[farthest]};
  }

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    List<Integer>[] graph = new ArrayList[n + 1];
    for (int i = 1; i <= n; i++) graph[i] = new ArrayList<>();

    for (int i = 0; i < n - 1; i++) {
      int u = sc.nextInt();
      int v = sc.nextInt();
      graph[u].add(v);
      graph[v].add(u);
    }

    int endpoint = bfs(graph, 1)[0];
    int diameter = bfs(graph, endpoint)[1];
    System.out.println(diameter);
  }
}

Python Solution

from collections import deque

n = int(input())
graph = [[] for _ in range(n + 1)]
for _ in range(n - 1):
    u, v = map(int, input().split())
    graph[u].append(v)
    graph[v].append(u)

def bfs(start):
    dist = [-1] * (n + 1)
    dist[start] = 0
    q = deque([start])
    while q:
        node = q.popleft()
        for nxt in graph[node]:
            if dist[nxt] == -1:
                dist[nxt] = dist[node] + 1
                q.append(nxt)
    farthest = max(range(1, n + 1), key=lambda x: dist[x])
    return farthest, dist[farthest]

endpoint, _ = bfs(1)
_, diameter = bfs(endpoint)
print(diameter)

Practice Challenge

Make the idea your own

Create a two-minute explanation of B Tree: define it, trace one example, name one edge case, and give the runtime of the main operation.

Tutoring Connection

Turn the topic into usable problem-solving skill

Students can use this page before a lesson, after a difficult homework assignment, or while preparing for AP Computer Science A extensions, Advanced Topics in CS, USACO growth, or a college data structures course.