💻 Programming

Recursion

Recursion

A programming technique in which a function calls itself. Consists of a base case and a recursive case, and is essential for tree traversal and divide-and-conquer algorithms.

📖 Detailed Explanation

Recursion is a programming technique in which a function calls itself to solve a problem. It is the core of the "Divide and Conquer" strategy, which solves a complex problem by breaking it down into smaller subproblems of the same structure. Recursive thinking is a very powerful tool in programming, and many algorithms and data structures are designed based on recursion.

A recursive function must contain two elements. The Base case is the termination condition that stops the recursive calls, and it is the simplest case that can no longer be broken down. The Recursive case is the part that breaks the problem down into smaller subproblems and calls itself. If there is no base case or it is never reached, the function falls into an infinite loop and a Stack Overflow occurs.

Tail Call Optimization (TCO) is an optimization technique in which the compiler reuses the stack frame when a recursive call is the last operation of a function. In ordinary recursion, a frame is pushed onto the stack with every call, but tail recursion prevents this. Languages such as Scheme, Scala, and Elixir support TCO, but JavaScript (specified in the ES6 specification but not implemented by most engines) and Python do not, so caution is needed with deep recursion.

Recursion is used in a variety of ways in practice. Tree traversal (preorder, inorder, postorder traversal) is a representative example of recursion. Quicksort and merge sort, which are divide-and-conquer algorithms, use recursion, and it is also essential in backtracking problems (N-Queens, maze search). When dealing with hierarchical structures such as directory traversal in a file system, JSON object parsing, and DOM tree traversal, recursion makes the code much more concise.

💻 Code Example

// 1. 팩토리얼 (기본 재귀)
function factorial(n) {
    // Base case: 종료 조건
    if (n <= 1) return 1;

    // Recursive case: 자기 자신 호출
    return n * factorial(n - 1);
}

console.log(factorial(5)); // 120 (5 * 4 * 3 * 2 * 1)


// 2. 피보나치 (비효율적인 재귀)
function fibonacciSlow(n) {
    if (n <= 1) return n;
    return fibonacciSlow(n - 1) + fibonacciSlow(n - 2);
    // 문제: 동일한 계산이 반복됨 (지수적 시간복잡도)
}


// 3. 피보나치 (메모이제이션으로 최적화)
function fibonacciMemo(n, memo = {}) {
    if (n in memo) return memo[n];  // 캐시된 결과 반환
    if (n <= 1) return n;

    memo[n] = fibonacciMemo(n - 1, memo) + fibonacciMemo(n - 2, memo);
    return memo[n];
}

console.log(fibonacciMemo(50)); // 12586269025 (빠르게 계산)


// 4. 꼬리 재귀 (Tail Recursion)
function factorialTail(n, acc = 1) {
    if (n <= 1) return acc;
    // 재귀 호출이 마지막 동작 (추가 연산 없음)
    return factorialTail(n - 1, n * acc);
}


// 5. 깊은 객체 탐색 (실무 활용)
function findValue(obj, targetKey) {
    for (const key in obj) {
        if (key === targetKey) return obj[key];

        if (typeof obj[key] === 'object' && obj[key] !== null) {
            const result = findValue(obj[key], targetKey);
            if (result !== undefined) return result;
        }
    }
    return undefined;
}

const data = {
    user: {
        profile: {
            name: '홍길동',
            contact: { email: 'hong@example.com' }
        }
    }
};

console.log(findValue(data, 'email')); // 'hong@example.com'
# 1. 팩토리얼
def factorial(n):
    if n <= 1:  # Base case
        return 1
    return n * factorial(n - 1)  # Recursive case

print(factorial(5))  # 120


# 2. 피보나치 (메모이제이션 with lru_cache)
from functools import lru_cache

@lru_cache(maxsize=None)
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(50))  # 12586269025


# 3. 리스트 합계 (반복문 대신 재귀)
def sum_list(lst):
    if not lst:  # Base case: 빈 리스트
        return 0
    return lst[0] + sum_list(lst[1:])  # 첫 요소 + 나머지 합

print(sum_list([1, 2, 3, 4, 5]))  # 15


# 4. 디렉토리 내 모든 파일 찾기
import os

def find_files(directory, extension):
    files = []
    for item in os.listdir(directory):
        path = os.path.join(directory, item)
        if os.path.isdir(path):
            # 재귀: 하위 디렉토리 탐색
            files.extend(find_files(path, extension))
        elif item.endswith(extension):
            files.append(path)
    return files

# python_files = find_files('/project', '.py')


# 5. 재귀 깊이 제한 변경 (주의해서 사용)
import sys
print(sys.getrecursionlimit())  # 기본값: 1000
# sys.setrecursionlimit(3000)  # 필요시 증가


# 6. 반복문으로 변환 (Stack Overflow 방지)
def factorial_iterative(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result
// 이진 트리 노드 정의
class TreeNode {
    constructor(val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

// 트리 생성
//       1
//      / \
//     2   3
//    / \
//   4   5
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);


// 1. 전위 순회 (Pre-order): 루트 -> 왼쪽 -> 오른쪽
function preorder(node) {
    if (!node) return;
    console.log(node.val);    // 현재 노드 방문
    preorder(node.left);       // 왼쪽 서브트리
    preorder(node.right);      // 오른쪽 서브트리
}
preorder(root);  // 1, 2, 4, 5, 3


// 2. 중위 순회 (In-order): 왼쪽 -> 루트 -> 오른쪽
function inorder(node) {
    if (!node) return;
    inorder(node.left);
    console.log(node.val);
    inorder(node.right);
}
inorder(root);  // 4, 2, 5, 1, 3


// 3. 후위 순회 (Post-order): 왼쪽 -> 오른쪽 -> 루트
function postorder(node) {
    if (!node) return;
    postorder(node.left);
    postorder(node.right);
    console.log(node.val);
}
postorder(root);  // 4, 5, 2, 3, 1


// 4. 트리 최대 깊이 구하기
function maxDepth(node) {
    if (!node) return 0;  // Base case

    const leftDepth = maxDepth(node.left);
    const rightDepth = maxDepth(node.right);

    return Math.max(leftDepth, rightDepth) + 1;
}
console.log(maxDepth(root));  // 3


// 5. 트리 모든 노드 합계
function sumTree(node) {
    if (!node) return 0;
    return node.val + sumTree(node.left) + sumTree(node.right);
}
console.log(sumTree(root));  // 15 (1+2+3+4+5)


// 6. 경로 찾기 (루트에서 특정 값까지)
function findPath(node, target, path = []) {
    if (!node) return null;

    path.push(node.val);

    if (node.val === target) return path;

    const leftPath = findPath(node.left, target, [...path]);
    if (leftPath) return leftPath;

    const rightPath = findPath(node.right, target, [...path]);
    if (rightPath) return rightPath;

    return null;
}
console.log(findPath(root, 5));  // [1, 2, 5]

🗣️ Say It Like This in Practice

💬 In an Interview (Recursion vs. Loops)
"Recursion makes code intuitive and is well suited to hierarchical structures such as trees or graphs. However, since a stack frame is pushed with every call, a stack overflow occurs if the depth is great. Loops do not use the stack, so they are memory-efficient, but the code becomes verbose when there are complex branches. I use recursion for tree traversal and a for loop for simple iteration."
💬 In a Code Review (Preventing Stack Overflow)
"The depth of this recursive function is determined by user input. If the maximum depth cannot be predicted, it is safer to switch to a loop or use an explicit stack. Also, in cases with many duplicate calculations like Fibonacci, please consider adding memoization to reduce the time complexity from O(2^n) to O(n)."
💬 When Explaining to a Colleague
"When thinking about recursion, you can start by 'assuming this function can already solve the smaller problem.' Just trust that factorial(n-1) already returns (n-1)!, and multiply it by n. If you define the base case well, the rest follows naturally."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Stack Overflow

If the recursion depth is too great, the call stack becomes full and the program halts. The limit is several thousand calls in JavaScript and 1000 by default in Python. If the depth is unpredictable or large, replace it with a loop, tail recursion (in languages that support TCO), or an explicit stack.

❌
Missing or unreachable base case

If there is no termination condition or it is set incorrectly, you fall into infinite recursion. Include edge cases, such as using `if (n <= 0)` instead of `if (n == 0)`. When writing a recursive function, always define "how does it stop?" first.

❌
Duplicate calculations (memoization not applied)

Simple recursive Fibonacci calculates fib(3) multiple times when computing fib(5). The time complexity becomes O(2^n), so even n=40 takes several seconds. Improve it to O(n) with memoization (result caching), or use the bottom-up approach of dynamic programming.

✅
Judging when recursion is appropriate

Recursion is effective for tree/graph traversal, divide and conquer (quicksort, merge sort), backtracking (N-Queens), and hierarchical data processing. For simple repetitive tasks (array sums, counting), loops are more efficient. Choose the tool that fits the characteristics of the problem.

🔗 Related Terms

📚 Learn More