Skip to content

Commit a4d36c8

Browse files
committed
100. Same Tree
1 parent b1bc659 commit a4d36c8

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

same-tree/socow.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""
2+
100. Same Tree
3+
4+
문제 요약
5+
- 두 이진 트리가 똑같은지 확인하기
6+
- 구조도 같고, 값도 같아야 True
7+
8+
문제 예시
9+
트리1: 트리2:
10+
1 1
11+
/ \ / \
12+
2 3 2 3
13+
→ True (완전 동일!)
14+
15+
트리1: 트리2:
16+
1 1
17+
/ \
18+
2 2
19+
→ False (구조가 다름!)
20+
21+
핵심 알고리즘
22+
- 패턴: 재귀 (DFS)
23+
- 시간복잡도: O(n) - 모든 노드 방문
24+
- 공간복잡도: O(h) - h는 트리 높이
25+
26+
핵심 아이디어
27+
1. 둘 다 None → True
28+
2. 하나만 None → False
29+
3. 값이 다름 → False
30+
4. 왼쪽 서브트리 비교 & 오른쪽 서브트리 비교
31+
"""
32+
33+
from typing import Optional
34+
35+
36+
class TreeNode:
37+
def __init__(self, val=0, left=None, right=None):
38+
self.val = val
39+
self.left = left
40+
self.right = right
41+
42+
43+
class Solution:
44+
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
45+
# 둘 다 None → 같음!
46+
if not p and not q:
47+
return True
48+
49+
# 하나만 None → 다름!
50+
if not p or not q:
51+
return False
52+
53+
# 값이 다름 → 다름!
54+
if p.val != q.val:
55+
return False
56+
57+
# 왼쪽끼리 비교 AND 오른쪽끼리 비교
58+
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

0 commit comments

Comments
 (0)