![[인프런 워밍업 클럽 스터디 3기] 2주차 미션 - 자료구조와 알고리즘](https://cdn.inflearn.com/public/files/blogs/d6314cfe-6ce7-4a4d-8a13-87494e707add/인프런 썸네일.png)
[인프런 워밍업 클럽 스터디 3기] 2주차 미션 - 자료구조와 알고리즘
7개월 전
자료구조와 알고리즘
재귀함수에서 기저조건을 만들지 않거나 잘못 설정했을 때 어떤 문제가 발생할 수 있나요?
재귀함수가 무한 호출 됩니다. 결국 콜 스택이 가득차 종료됩니다.
0부터 입력 n까지 홀수의 합을 더하는 재귀 함수를 만들어보세요.
function sumOdd(n) {
if (n <= 0) return 0; // 종료 조건
if (n % 2 === 0) n -= 1;
return n + sumOdd(n - 2); //재귀 로직, 하위 문제로 나눔
}
다음 코드는 매개변수로 주어진 파일 경로(.는 현재 디렉토리)에 있는 하위 모든 파일과 디렉토리를 출력하는 코드입니다. 다음 코드를 재귀 함수를 이용하는 코드로 변경해보세요.
const fs = require("fs");
const path = require("path");
function traverseDirectory2(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);
traverseDirectory2(filePath); // 디렉토리면 재귀 호출
} else {
console.log('파일:', filePath);
}
}
}
traverseDirectory2("."); // 현재 디렉토리 탐색
댓글을 작성해보세요.