AP Computer Science AUnit 4 · 4.9Often tested

Recursion · Đệ quy

ENGLISH

Recursion is when a method calls itself to solve a smaller version of the same problem, until it reaches a base case that can be answered directly.

TIẾNG VIỆT

Đệ quy là khi một phương thức gọi lại chính nó để giải một phiên bản nhỏ hơn của cùng bài toán, cho tới khi gặp trường hợp cơ sở có thể trả lời ngay.

Quick intuition

ENGLISH

Like a ticket queue: you ask the person ahead "what's your position?". They ask the person ahead of them… until the first person says "1". The answer travels back, each person adding 1.

TIẾNG VIỆT

Giống xếp hàng mua vé: bạn hỏi người phía trước "anh đứng thứ mấy?". Người đó lại hỏi người trước nữa… tới người đầu hàng trả lời "thứ 1". Câu trả lời truyền ngược lại, mỗi người cộng thêm 1.

Code pattern

public static int sumTo(int n) { if (n == 0) return 0; // base case return n + sumTo(n - 1); // recursive step } // sumTo(3) = 3 + sumTo(2) = 3 + 2 + sumTo(1) = 3 + 2 + 1 + 0 = 6

Each call is pushed onto the call stack and only returns its result once the call inside it has finished.

Common mistakes

Forgetting the base case, or getting it wrong

With no stopping point, the method calls itself forever and eventually throws a StackOverflowError. Always ask yourself: for the smallest input, what's the answer?

A recursive step that doesn't shrink the problem

Calling sumTo(n) inside sumTo(n) never moves toward the base case. The argument has to change in the direction of the stopping point.

Reading results in call order instead of return order

A print statement placed after the recursive call runs in reverse order. Draw the call tree to keep track.

Exam tips

  • For "what does f(4) return?" MCQs: write out each level of calls on paper and fill in the return values from the bottom up.
  • AP CSA only asks you to read and trace recursion in the MCQ section. You're not required to write recursive code in the FRQs.
  • Merge sort and binary search can both be written recursively. Spotting this pattern helps you read code faster.

Origins

  • 19th centuryInductive definitions in mathematics, such as the Fibonacci sequence.
  • 1930sThe theory of recursive functions, a foundation of computer science.
  • 1960sProgramming languages support recursive calls thanks to the call stack.

From the Latin recurrere, "to run back".