Skip to content

[moonjonghoo]25.02.11#41

Merged
JooKangsan merged 21 commits intomainfrom
jh
Feb 13, 2025
Merged

[moonjonghoo]25.02.11#41
JooKangsan merged 21 commits intomainfrom
jh

Conversation

@Moonjonghoo
Copy link
Collaborator

PR 제목은 [user_name] yy.mm.dd 형식으로 작성 (스터디 날짜)

📌 푼 문제

문제이름 문제링크
이진 트리의 최대 깊이 https://leetcode.com/problems/maximum-depth-of-binary-tree/
이진 트리의 중위 순회 https://leetcode.com/problems/binary-tree-inorder-traversal/
같은 트리인지 비교 https://leetcode.com/problems/same-tree/description/
이진 트리 반전 https://leetcode.com/problems/invert-binary-tree/

📝 간단한 풀이 과정

Binary Tree Inorder Traversal

  • 중위 순회(Inorder Traversal)를 수행하여 이진 트리의 값을 배열에 저장하는 문제.
  • 왼쪽 서브트리를 방문한 후, 현재 노드를 방문하고, 오른쪽 서브트리를 방문하는 방식으로 구현됨.
var inorderTraversal = function (root) {
  const result = [];

  const traverse = (node) => {
    if (node === null) return;
    traverse(node.left); // 왼쪽 서브트리 방문
    result.push(node.val); // 현재 노드 방문
    traverse(node.right); // 오른쪽 서브트리 방문
  };

  traverse(root);
  return result;
};

📝 간단한 풀이 과정

Invert Binary Tree

  • 이진 트리의 모든 노드를 좌우 반전시키는 문제.
  • 각 노드에서 왼쪽과 오른쪽 자식 노드를 교환하고, 재귀적으로 반전을 진행함.
var invertTree = function (root) {
  if (root === null) {
    return null;
  }

  // 왼쪽과 오른쪽 자식 노드를 교환
  const temp = root.left;
  root.left = root.right;
  root.right = temp;

  // 재귀적으로 자식 노드들을 반전
  invertTree(root.left);
  invertTree(root.right);

  return root;
};

📝 간단한 풀이 과정

Maximum Depth of Binary Tree

  • 이진 트리의 최대 깊이를 구하는 문제.
  • 루트부터 가장 깊은 리프 노드까지의 거리(레벨)를 재귀적으로 계산.
var maxDepth = function (root) {
  if (!root) return 0;
  return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
};

📝 간단한 풀이 과정

Same Tree

  • 두 개의 이진 트리가 동일한 구조와 값을 가지는지 비교하는 문제.
  • 각 노드를 비교하며, 좌우 서브트리도 재귀적으로 검사함.
var isSameTree = function (p, q) {
  // 두 노드가 모두 null인 경우
  if (p === null && q === null) {
    return true;
  }
  // 한 노드만 null인 경우
  if (p === null || q === null) {
    return false;
  }
  // 노드의 값이 다른 경우
  if (p.val !== q.val) {
    return false;
  }
  // 왼쪽 및 오른쪽 서브트리를 재귀적으로 비교
  return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};


Copy link
Collaborator

@JooKangsan JooKangsan 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 d8b08dc 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.

2 participants