Skip to content

Comments

[JustDevRae] 25.02.07#39

Merged
JooKangsan merged 30 commits intomainfrom
JustDevRae
Feb 13, 2025
Merged

[JustDevRae] 25.02.07#39
JooKangsan merged 30 commits intomainfrom
JustDevRae

Conversation

@JustDevRae
Copy link
Collaborator

📌 푼 문제


📝 간단한 풀이 과정

이진 트리의 최대 깊이

DFS(재귀)를 사용하여 루트에서 시작해 왼쪽과 오른쪽 서브트리의 깊이를 구하고 최대값을 반환하는 방식으로 해결했습니다.

function maxDepth(root) {
  if (!root) return 0;

  return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}

이진 트리의 중위 순회

스택을 사용하여 트리를 왼쪽부터 탐색하고, 스택에서 값을 꺼내며 오른쪽으로 이동하는 방식으로 해결했습니다. 중위 순회의 순서를 유지하면서 노드 값을 배열에 추가하는 방식으로 동작합니다.

function inorderTraversal(root) {
  let result = [];
  let stack = [];
  let current = root;

  while (current || stack.length) {
    while (current) {
      stack.push(current); 
      current = current.left; 
    }

    current = stack.pop(); 
    result.push(current.val); 
    current = current.right;
  }

  return result;
}

같은 트리인지 비교

두 트리를 동시에 순회하면서 재귀적으로 왼쪽과 오른쪽 서브트리를 비교하며 하나라도 다르면 false를 반환하는 방식으로 해결했습니다.

function isSameTree(p, q) {
  
  if (!p && !q) return true;
  
  if (!p || !q) return false;
  
  if (p.val !== q.val) return false;

  return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}

이진 트리 반전

각 노드에서 좌우를 교환한 후, DFS를 통해 재귀적으로 모든 노드에 대해 동일한 연산을 수행하는 방식으로 해결했습니다.

function invertTree(root) {
  if (!root) return null;

  [root.left, root.right] = [root.right, root.left];

  invertTree(root.left);
  invertTree(root.right);

  return root;
}

이진 트리 레벨 순서 순회

BFS(큐)를 사용하여 층별로 탐색하며, 각 층을 배열에 저장한 후 최종 결과를 반환하는 방식으로 해결했습니다.

function levelOrder(root) {
  if (!root) return [];

  let result = [];
  let queue = [root];

  while (queue.length > 0) {
    let level = [];
    let size = queue.length;

    for (let i = 0; i < size; i++) {
      let node = queue.shift();
      level.push(node.val);

      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
    }

    result.push(level);
  }

  return result;
}

Copy link
Collaborator

@tkddbs587 tkddbs587 left a comment

Choose a reason for hiding this comment

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

수고하셨습니다 승래님!! 💪🏻

@JooKangsan JooKangsan merged commit 19a142d into main Feb 13, 2025
3 checks passed
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