LOGBOOK

HELP

1 / 73
time's up — finish this card
Other keys: show • Space: good • 1-4: rate • 0: skip • 5: flag
Topic Trees: Structure, Storage and Traversals

Question

What is the depth of a node, and how is it computed?

Answer

The depth of a node is the number of its ancestors (not counting itself), which equals the number of edges on the path up to the root; the root has depth 0, and every other node has depth 1 + the depth of its parent.

The definition gives a recursive algorithm directly:

Algorithm depth(T, v)
  if v is the root of T then
    return 0
  else
    return 1 + depth(T, v.parent())

It walks upwards, one parent at a time, until it reaches the root. So its running time is proportional to the depth itself: $O(d_v + 1)$ for a node at depth $d_v$, and $O(n)$ in the worst case of a tree that is one long chain.

In a document outline, depth corresponds to the heading level: the title has depth 0, the chapters depth 1, the sections depth 2.

Gotcha: depth counts edges, not nodes. A child of the root has one ancestor, so its depth is 1, even though the path from the root to it contains two nodes.

or press any other key
Topic Asymptotic Analysis, O-Notation and Recursion

Question

Write a recursive method that computes $\sum_{i=0}^{n} i$, and compare it with the closed form.

Answer

Same skeleton as factorial — base case 0, otherwise n + recursiveSum(n-1) — but the closed form $\frac{n(n+1)}{2}$ gets the same answer in $O(1)$.

public static int recursiveSum(int n) {
  if (n == 0) {
    return 0;                        // base case: empty sum is 0
  } else {
    return n + recursiveSum(n - 1);  // n plus the sum of everything below
  }
}

For $n = 100$ both routes give 5050:

Approach Cost Memory
recursiveSum(100) $O(n)$ — one call per value $O(n)$ — one stack frame per call
100 * 101 / 2 $O(1)$ $O(1)$

Note the base case: for a sum the neutral element is 0, while for a product (factorial) it is 1. Returning the wrong one gives an answer that is wrong by a constant or collapses to zero — a classic off-by-identity bug.

The real lesson: recursion mirrors the definition of the sum, and that is genuinely valuable when no closed form exists. But when one does, it wins outright — $O(1)$ against $O(n)$ time and $O(n)$ stack. Knowing the mathematics of your problem beats implementing its definition faithfully.

or press any other key