Skip to content

Commit 7c85ff4

Browse files
committed
same-tree solution (py)
1 parent 192433f commit 7c85ff4

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

same-tree/hi-rachel.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
from typing import Optional
2+
3+
# Definition for a binary tree node.
4+
class TreeNode:
5+
def __init__(self, val=0, left=None, right=None):
6+
self.val = val
7+
self.left = left
8+
self.right = right
9+
10+
"""
11+
재귀 풀아
12+
13+
TC: O(N), 양 트리의 각 노드를 상대로 재귀함수를 딱 1번씩만 호출하기 때문
14+
SC: O(N), 공간복잡도 = 콜스택의 최대 높이(노드의 수)
15+
"""
16+
class Solution:
17+
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
18+
# 둘 다 null이면 True 반환
19+
if not p and not q:
20+
return True
21+
# 둘 중 하나면 null이면 False 반환
22+
if not p or not q:
23+
return False
24+
# val이 서로 다르면 탐색 중단, False 반환
25+
if p.val != q.val:
26+
return False
27+
# 현재 node의 val이 같다면, 좌우측 자식 트리도 같은지 확인 -> 재귀 호출
28+
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
29+
30+
31+
"""
32+
스택 풀이
33+
34+
TC: O(N)
35+
SC: O(N)
36+
"""
37+
38+
class Solution:
39+
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
40+
stack = [(p, q)]
41+
42+
while stack:
43+
p, q = stack.pop()
44+
if not p and not q:
45+
continue
46+
if not p or not q:
47+
return False
48+
if p.val != q.val:
49+
return False
50+
stack.append((p.left, q.left))
51+
stack.append((p.right, q.right))
52+
return True

0 commit comments

Comments
 (0)