Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions subtree-of-another-tree/reeseo3o.js

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🏷️ 알고리즘 패턴 분석

  • 패턴: DFS
  • 설명: 이 코드는 재귀 호출을 통해 트리의 모든 노드를 방문하며 서브트리 여부를 검사하는 방식으로, 깊이 우선 탐색(DFS) 패턴에 속합니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(n * m)
Space O(h + m)

피드백: 전체 트리의 각 노드에 대해 서브트리 일치 여부를 검사하는데, 각 검사에서 두 트리의 노드 수에 비례하는 시간이 소요됩니다. 따라서 최악의 경우 시간 복잡도는 O(n * m)입니다.

개선 제안: 현재 구현이 적절해 보입니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Time Complexity: O(n*m)
// Space Complexity: O(n+m)

const isSubtree = (root, subRoot) => {
const isSame = (a, b) => {
if (!a && !b) return true;
if (!a || !b) return false;
if (a.val !== b.val) return false;
return isSame(a.left, b.left) && isSame(a.right, b.right);
};

if (!root) return false;
return (
isSame(root, subRoot) ||
isSubtree(root.left, subRoot) ||
isSubtree(root.right, subRoot)
);
};
Loading