![[인프런 워밍업 클럽 3기 - CS] 2주차 자료구조와 알고리즘 미션](https://cdn.inflearn.com/public/files/blogs/0324d058-c4ed-458b-bda6-2123597abe4b/image (23).png)
[인프런 워밍업 클럽 3기 - CS] 2주차 자료구조와 알고리즘 미션
1개월 전
1. 재귀함수에서 기저조건을 만들지 않거나 잘못 설정했을 때 어떤 문제가 발생할 수 있나요?
콜스택이 계속 쌓여서 메모리가 부족해져서 프로세스가 비정상 종료될 수 있다.
2. 0부터 입력 n까지 홀수의 합을 더하는 재귀 함수를 만들어보세요.
function sumOdd(n) {
if (n % 2 === 0) return sumOdd(n - 1);
if (n === 1) return 1;
return sumOdd(n - 2) + n;
}
3. 다음 코드는 매개변수로 주어진 파일 경로(.는 현재 디렉토리)에 있는 하위 모든 파일과 디렉토리를 출력하는 코드입니다. 다음 코드를 재귀 함수를 이용하는 코드로 변경해보세요.
const fs = require("fs"); // 파일을 이용하는 모듈
const path = require("path"); // 폴더와 파일의 경로를 지정해주는 모듈
function traverseDirectory1(directory) {
const files = fs.readdirSync(directory); // 인자로 주어진 경로의 디렉토리에 있는 파일or디렉토리들
for (const file of files) { // 현재 디렉토리의 모든 파일or디렉토리 순회
const filePath = path.join(directory, file); // directory와 file을 하나의 경로로 합쳐줌
const fileStatus = fs.statSync(filePath); // 파일정보 얻기
if (fileStatus.isDirectory()) { // 해당 파일이 디렉토리라면
console.log('디렉토리:', filePath);
traverseDirectory1(filePath);
} else { // 해당 파일이 파일이라면
console.log('파일:', filePath);
}
}
}
댓글을 작성해보세요.