Skip to content

[지원] 8-3. 이진트리순회 #327

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 4 commits into
base: main
Choose a base branch
from
Open

[지원] 8-3. 이진트리순회 #327

wants to merge 4 commits into from

Conversation

seolsis
Copy link
Contributor

@seolsis seolsis commented Nov 21, 2024

✔ 문제 제목: 이진트리순회

✔ 문제 유형: 재귀

✔ 문제 풀이 날짜: 11.21

💡 문제 분석 요약

전위순회, 후위순회 출력

💡 알고리즘 설계

  • 전위순회는 현재 노드 번호를 추가하고 왼쪽 자식 재귀호출, 오른쪽 자식 재귀호출
  • 후위 순회는 왼쪽 자식 재귀호출, 오른쪽 자식 재귀호출하고 현재 노드번호 추가

💡코드

function solution(n) {
  let answer = {
    preOrder: "",
    postOrder: "",
  };

  const tree = {
    1: [2, 3],
    2: [4, 5],
    3: [6, 7],
    4: [null, null],
    5: [null, null],
    6: [null, null],
    7: [null, null],
  };

  function preOrder(node) {
    if (!node) return; // 기저조건
    answer.preOrder += node + " "; // 현재 노드 번호 추가
    preOrder(tree[node][0]); // 왼쪽 자식을 재귀 호출
    preOrder(tree[node][1]); // 오른쪽 자식을 재귀 호출
  }

  function postOrder(node) {
    if (!node) return;
    postOrder(tree[node][0]);
    postOrder(tree[node][1]);
    answer.postOrder += node + " ";
  }

  preOrder(n);
  postOrder(n);
  return answer;
}

console.log(solution(1));

💡 시간복잡도

O(N) => 트리의 모든 노드를 정확히 한 번 방문하므로, 시간복잡도는 노드의 수 N에 비례

💡 느낀 점 or 기억할 정보

  • 재귀 어려워요 🍃

Copy link
Contributor

@devwqc devwqc left a comment

Choose a reason for hiding this comment

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

좋아요~ 🌟

오! 되게 참신한 방식으로 접근하셨네요.
별도로 tee 객체 선언하지 않고 출력하는 것도 해보면 좋을 것 같아요. 👍🎉👍🎉👍🎉👍🎉👍🎉👍🎉👍🎉👍🎉👍🎉👍🎉👍🎉👍🎉👍🎉👍🎉

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.

2 participants