Skip to content

Commit 65c6b77

Browse files
committed
subtree-of-another-tree solution (py)
1 parent 973841f commit 65c6b77

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

subtree-of-another-tree/hi-rachel.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
https://leetcode.com/problems/subtree-of-another-tree/description/
3+
4+
두 개의 이진 트리 root와 subRoot의 루트(최상위 노드)가 주어졌을 때,
5+
root의 하위 트리 중 subRoot와 동일한 구조와 값이 있는 경우 참을 반환하고 그렇지 않은 경우 거짓을 반환
6+
7+
TC: O(n * m), n: root의 노드 수, m: subRoot의 노드 수
8+
SC: O(n + m)
9+
"""
10+
11+
from typing import Optional
12+
13+
# Definition for a binary tree node.
14+
class TreeNode:
15+
def __init__(self, val=0, left=None, right=None):
16+
self.val = val
17+
self.left = left
18+
self.right = right
19+
20+
class Solution:
21+
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
22+
if not root:
23+
return False
24+
if not subRoot:
25+
return True
26+
27+
def isSameTree(p, q):
28+
# 둘 중 하나라도 None 이면,
29+
if not p or not q:
30+
# 둘 다 None 일 때만 True
31+
return not p and not q
32+
# 같이 다르면 False
33+
if p.val != q.val:
34+
return False
35+
# 왼쪽과 오른쪽 서브트리를 재귀적으로 비교
36+
return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
37+
38+
# root에서 시작해 subRoot와 동일한 구조의 트리인지 확인
39+
if isSameTree(root, subRoot):
40+
return True
41+
42+
# 왼쪽 또는 오른쪽 서브트리 중 하나라도 subRoot와 같은 트리가 있는지 재귀 탐색
43+
return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)

0 commit comments

Comments
 (0)