🎁[속보] 인프런 내 깜짝 선물 출현 중🎁

[인프런 워밍업 클럽 3기 CS] 자료구조 및 알고리즘 2주 차 미션

[인프런 워밍업 클럽 3기 CS] 자료구조 및 알고리즘 2주 차 미션

자료구조와 알고리즘

1. 재귀함수에서 기저 조건을 만들지 않거나 잘못 설정했을 때 발생하는 문제

• 무한 루프(무한 재귀) 발생 → 스택이 계속 쌓이며 Stack Overflow(스택 오버플로우) 발생

• 잘못된 결과 반환 → 기저 조건을 잘못 설정하면 원하는 값을 반환하지 못함

 

2. 0부터 입력 n까지 홀수의 합을 구하는 재귀 함수

function sumOdd(n) {
  if (n <= 0) return 0; // 기저 조건
  return (n % 2 !== 0 ? n : 0) + sumOdd(n - 1); // n이 홀수면 더함
}

console.log(sumOdd(10)); // 25

 

3. 재귀를 이용한 디렉토리 탐색 코드

const fs = require("fs"); // 파일 시스템 모듈
const path = require("path"); // 경로 관련 모듈

function traverseDirectory(directory) {
    const files = fs.readdirSync(directory); // 현재 디렉토리의 파일 목록

    for (const file of files) {
        const filePath = path.join(directory, file); // 현재 파일 경로
        const fileStatus = fs.statSync(filePath); // 파일 상태 정보 가져오기

        if (fileStatus.isDirectory()) {
            console.log('디렉토리:', filePath);
            traverseDirectory(filePath); // 재귀 호출
        } else {
            console.log('파일:', filePath);
        }
    }
}

traverseDirectory("."); // 현재 디렉토리부터 탐색 시작

재귀를 사용하여 모든 하위 디렉토리를 탐색하면서 파일과 폴더를 출력함.

댓글을 작성해보세요.


채널톡 아이콘