Skip to content

[정봉찬] 9-5. 이진트리 넓이우선탐색(BFS) #218

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

devwqc
Copy link
Contributor

@devwqc devwqc commented Sep 7, 2024

✔ 문제 제목: 이진트리 넓이우선탐색(BFS)

✔ 문제 유형: BFS

✔ 문제 풀이 날짜: 2024-09-08

💡 문제 분석 요약

  • 이진트리를 넓이우선탐색해 보세요.
  • 1 2 3 4 5 6 7

💡 알고리즘 설계

  • 현재 노드 기준 왼쪽 자식 노드는 (현재 노드 x 2), 오른쪽 자식 노드는 (현재 노드 x 2 + 1)
  • 노드를 담을 큐를 빈 배열로 선언한다.
  • 재귀를 돌면서 큐에서 노드를 꺼내고 왼쪽 자식 노드, 오른쪽 자식 노드를 넣는다.
  • 꺼낸 노드가 7이면 함수를 종료한다.

💡코드

function solution() {
  let answer = '';
  const queue = [];

  function BFS() {
    const node = queue.shift();
    answer += node + ' ';

    if (node === 7) {
      return;
    }

    const left = node * 2;
    const right = node * 2 + 1;

    queue.push(left);
    queue.push(right);

    BFS();
  }

  queue.push(1);
  BFS(0);

  return answer;
}

console.log(solution());  // 1 2 3 4 5 6 7

💡 시간복잡도

  • O(n)

💡 틀린 이유와 틀린 부분 수정 or 다른 풀이

  • ⭐ while문 풀이
  • 현재 노드 기준 왼쪽 자식 노드는 (현재 노드 x 2), 오른쪽 자식 노드는 (현재 노드 x 2 + 1)
  • 노드를 담을 큐를 빈 배열로 선언한다.
  • 큐가 비어있지 않은 조건으로 while문을 돌면서 큐에서 노드를 꺼내고 왼쪽 자식 노드, 오른쪽 자식 노드를 넣는다.
function solution2() {
  let answer = '';

  const queue = [];

  queue.push(1);
  while (queue.length) {
    const node = queue.shift();
    answer += node + ' ';

    for (const next of [node * 2, node * 2 + 1]) {
      if (next > 7) {
        continue;
      }

      queue.push(next);
    }
  }

  return answer;
}

console.log(solution2()); // 1 2 3 4 5 6 7

💡 느낀 점 or 기억할 정보

  • 재귀 함수로 풀면 안 될 거 같은 느낌이다.

Copy link
Contributor

@ayoung-iya ayoung-iya left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DFS 풀면서 계속 재귀함수를 사용해서 일단 재귀함수로 적고 시작하게되는 그런 것도 있더라구요 🤔 그래도 스스로 큐를 생각하시고 푼 모습이 멋지십니다~👍

Copy link
Contributor

@Seoin02 Seoin02 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

와 벌써 이 문제를 4주 전에 풀이했다니 믿기지 않군요 시간 넘 빨라요...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants