티스토리 뷰
https://leetcode.com/problems/subtree-of-another-tree/
Subtree of Another Tree - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com

subRoot 노드가 root 노드의 subtree인지 확인하는 문제입니다.
노드의 val, left, right가 같은지 확인하면서 들어가야해서 두개의 재귀함수가 필요했습니다.
None처리가 굉장히 복잡했던 문제..
dfs함수는 root함수를 dfs로 탐색하고, compare_tree는 하나씩 들어갈때마다 노드가 같은지 확인하는 함수입니다.
class Solution:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
def compare_tree(a, b):
if a is None and b is None:
return True
# 둘 중 하나만 None이면 False
if (a is None or b is None) or a.val != b.val:
return False
# left, right 둘 다 같을경우 True
return compare_tree(a.left, b.left) and compare_tree(a.right, b.right)
def dfs(node, subRoot):
if compare_tree(node, subRoot):
return True
if node:
return dfs(node.left, subRoot) or dfs(node.right, subRoot)
# 둘 다 None인경우 True
return node == subRoot
return dfs(root, subRoot)
'ALGORITHM > LeetCode' 카테고리의 다른 글
[leetcode] count-items-matching-a-rule.py (0) | 2022.02.20 |
---|---|
[LeetCode] sort-integers-by-the-number-of-1-bits.py (0) | 2022.02.06 |
[leetcode] merge-two-sorted-lists.py (0) | 2021.12.26 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 백준
- conTeXt
- 팰린드롬수
- ManyToMany
- 의대 신경학 강의
- 파이썬
- Two Scoops of Django
- gunicorn
- query
- django
- go
- 독후감
- for-else
- 프로그래머스
- taggit
- 방금그곡
- go context
- 소프트웨어 장인
- leetcode
- sql lite
- dfs
- stdout
- Python
- 문자열 뒤집기
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함