Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson2 / 31

    The leap of faith (the skill that makes recursion click)

    Work this problem first

    A leaf has height 1 under this lesson’s node-count convention. Design CountLeaves for the same finite proper tree before reading the reference functions. Write its null case, leaf case and combining step; check a two-node chain and a root with two leaves.

    Predict before running

    The proper tree contains a root and two leaf children. Which result pair matches Count and Height as defined here?

    A Count=2, Height=3.
    B Count=3, Height=3.
    C Count=3, Height=2.
    D Count=2, Height=2.
    Show answer

    Correct answer: C

    Count adds both child counts and the current node. Height adds one to the larger child height, so branching increases count without adding another level.

    Hint: Count combines with addition; Height combines with maximum.

    Why tracing does not scale

    The usual block with recursion is trying to follow every call. That works for SumTo(4). It falls apart at depth three of a tree, where each call branches again. People get lost, decide recursion is confusing, and avoid it.

    Experienced developers do not need to trace every call while designing the function. Small traces and tests remain useful for debugging. They treat the recursive call exactly like a library call. You trust Math.Sqrt(2) without reading its source. In the same way, when you write Height(node), you trust that Height(node.Left) returns the correct height of the left subtree.

    The three questions

    When you write a recursive function, answer three questions, in this order:

    1. What does the function promise to return? Say it in one sentence. "Height(n) returns the number of nodes on the longest path from n down to a leaf, and 0 for null."
    2. What is the smallest input, and what is its answer? "For null, the height is 0."
    3. If the smaller calls keep their promise, how do I build my answer from theirs? "My height is 1 plus the larger of my children's heights."

    With valid inputs, correct arithmetic, and recursive calls that strictly decrease a well-founded measure, these answers establish functional correctness. Resource limits such as stack depth are a separate concern. This is mathematical induction: prove the base case, prove that each step follows from the step below it, and the whole ladder holds. You do not need to climb the ladder to know it is safe.

    The trap: answering question 3 without question 1

    Most wrong recursive functions are wrong because the promise in question 1 was never stated. For example, people mix "height counted in nodes" with "height counted in edges". Then the base case returns 0 for null in one place and -1 in another, and the answer is off by one. Writing the promise down as a comment before you code prevents this.

    Worked example: seven functions, one pattern (.NET 10)

    The tree in this example is a small binary search tree:

    Text
              8
            /   \
           3     10
          / \      \
         1   6      14
            / \    /
           4   7  13

    Each function states or relies on a base case, does local work and trusts smaller calls. Max requires a nonempty tree instead of accepting null. Assume finite proper trees without cycles or shared nodes; Count/Sum arithmetic, including intermediate sums, must fit int. The string functions require non-null strings and operate on ordinal UTF-16 code units, not general Unicode grapheme clusters. Their copying cost is discussed below.

    C#
    // L02: the leap of faith. Each function trusts the recursive call on a smaller input
    // and only does one step of work. A tiny tree makes the results easy to check by hand.
    var tree = new Node(8,
        new Node(3, new Node(1), new Node(6, new Node(4), new Node(7))),
        new Node(10, null, new Node(14, new Node(13), null)));
    
    Console.WriteLine($"Count     = {Count(tree)}");
    Console.WriteLine($"Height    = {Height(tree)}");
    Console.WriteLine($"Sum       = {Sum(tree)}");
    Console.WriteLine($"Max       = {Max(tree)}");
    Console.WriteLine($"Contains 6 = {Contains(tree, 6)}, Contains 5 = {Contains(tree, 5)}");
    Console.WriteLine($"Reverse(\"recursion\") = {Reverse("recursion")}");
    Console.WriteLine($"IsPalindrome(\"racecar\") = {IsPalindrome("racecar")}, IsPalindrome(\"rotor!\") = {IsPalindrome("rotor!")}");
    
    // Each method: a base case matching its contract, then local work + trusted smaller calls.
    static int Count(Node? n) => n is null ? 0 : 1 + Count(n.Left) + Count(n.Right);
    static int Height(Node? n) => n is null ? 0 : 1 + Math.Max(Height(n.Left), Height(n.Right));
    static int Sum(Node? n) => n is null ? 0 : n.Value + Sum(n.Left) + Sum(n.Right);
    static int Max(Node n)
    {
        int best = n.Value;
        if (n.Left is not null) best = Math.Max(best, Max(n.Left));
        if (n.Right is not null) best = Math.Max(best, Max(n.Right));
        return best;
    }
    static bool Contains(Node? n, int x) => n is not null && (n.Value == x || Contains(n.Left, x) || Contains(n.Right, x));
    static string Reverse(string s) => s.Length <= 1 ? s : Reverse(s[1..]) + s[0];
    static bool IsPalindrome(string s) => s.Length <= 1 || (s[0] == s[^1] && IsPalindrome(s[1..^1]));
    
    record Node(int Value, Node? Left = null, Node? Right = null);

    Real output:

    Text
    Count     = 9
    Height    = 4
    Sum       = 66
    Max       = 14
    Contains 6 = True, Contains 5 = False
    Reverse("recursion") = noisrucer
    IsPalindrome("racecar") = True, IsPalindrome("rotor!") = False

    Checking the output by the three questions

    functionpromisebase casecombine stepresult
    Countnumber of nodesnull gives 01 + left + right9 nodes
    Heightnodes on the longest root-to-leaf pathnull gives 01 + max(left, right)4 (8, 3, 6, 4)
    Sumsum of valuesnull gives 0value + left + right66
    Maxlargest value (non-empty tree)a node with no children gives its valuemax of value and each child's max14
    Containsis x in the treenull gives falsehere, or left, or right6 yes, 5 no
    Reversereverse the UTF-16 code unitslength 0 or 1 returns inputreverse suffix, append first code unitnoisrucer
    IsPalindromecode units read the same in both directionslength 0 or 1 is trueouter code units equal and inner part is a palindromeracecar yes

    Notice Max. It has no null case because there is no maximum value for an empty tree under this int-returning contract. Another API could explicitly return a nullable result or report an error. Its promise is "for a non-empty tree", so it only recurses into children that exist. Stating the promise tells you which base case you need.

    Notice also that Contains uses ||, which short-circuits: once the left subtree finds the value, the right subtree is never searched. Recursion and normal C# operators combine naturally. This Contains is a general tree traversal: it does not use the example tree’s BST ordering. Its worst-case time is O(n), even for a balanced tree; balance reduces its depth, not the number of nodes it may examine.

    Compare your trace

    SubtreeCountHeight in nodesLeaf count
    Empty000
    One leaf111
    Root with one leaf child221
    Root with two leaf children322

    A note on the string examples

    For Reverse, proper nonempty suffix slices copy characters, and repeated concatenation copies growing results. Across the recursion this is O(n²) character work and cumulative allocated character storage, plus O(n) recursive depth and an O(n) final result. Cumulative allocation is not a measurement of peak live memory: retained suffix references can also be costly, and exact liveness depends on the runtime.

    IsPalindrome also copies progressively smaller inner substrings, so its worst-case character work/allocation is O(n²), although a mismatch at the first pair can return immediately. Use indexes without slicing for O(n) worst-case time; recursion still has O(n) depth unless replaced with an O(1)-auxiliary-space two-pointer loop. For Reverse, passing indexes but keeping repeated string concatenation is still quadratic: write into a suitably sized mutable buffer, then construct the result once, for linear character work.

    These examples are ordinal and case-sensitive; spaces and punctuation count. Reversing UTF-16 code units can split a surrogate pair, and code-unit palindrome checks are not a general human-text definition. Choose code units, Unicode scalar values or grapheme clusters deliberately before designing a production text algorithm.

    How to explain your function out loud

    Interviewers want to hear the three answers. A good script for Height:

    "Height returns the number of nodes on the longest downward path. An empty tree has height zero. Otherwise I assume the recursive calls give me the heights of the two subtrees, take the larger one and add one for this node. Each node is visited once, so it is O(n) time and O(h) stack space, where h is the height."

    That last sentence matters. Maximum recursive depth tracks the height of the tree, with possibly one additional null-child call. For a balanced tree that is about log n. For a tree that is really a linked list, it is n, and that can overflow the stack (When to use recursion and when to prefer a loop).

    Practice: write these with the three questions

    1. CountLeaves(node): the number of nodes with no children.
    2. Mirror(node): return a new tree with left and right swapped at every level.
    3. SumDigits(n): the sum of the decimal digits of a non-negative int (SumDigits(1234) = 10).

    For each one, write the promise as a comment first, then the base case, then the combine step. Only then run it.

    Transfer drill: attempt before checking

    Give the three cases for CountLeaves. What changes if the input is a cyclic graph rather than a finite proper tree?

    Write your reasoning and a boundary test before reading the answer.

    Check your reasoning

    Return 0 for null, 1 for a node with no children, otherwise CountLeaves(left)+CountLeaves(right). A cycle invalidates the strict-subtree progress argument; define graph semantics and visited/cycle handling instead of applying this tree recurrence unchanged.

    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 28 Oct 2026 ·