| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 | 31 |
Tags
- BFS
- 아니메컵
- 27448
- populating next right pointers in each node
- 힙 정렬
- 딥러닝
- 백준
- 구현
- dp
- lgb
- 코딩
- 17070
- T tree
- C
- 모두의 꿈
- 파이썬
- 코테
- python
- 부분수열의 합2
- 정렬
- 코딩테스트
- 스펨메일 분류
- 2247
- 코복장
- dfs
- 샤논 엔트로피
- 다이나믹 프로그래밍
- 정답코드
- ps
- 실질적 약수
Archives
- Today
- Total
코딩복습장
LeetCode: SameTree 본문
728x90
Given the roots of two binary trees p and q, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
Example 1:

Input: p = [1,2,3], q = [1,2,3]
Output: true
Example 2:

Input: p = [1,2], q = [1,null,2]
Output: false
Example 3:

Input: p = [1,2,1], q = [1,1,2]
Output: false
Constraints:
- The number of nodes in both trees is in the range [0, 100].
- -10^4 <= Node.val <= 10^4
이 문제는 Tree를 재귀적으로 순회하며 값과 구조가 같은지 확인하는 문제이다.
풀이 방식은 다음과 같다.
1. 두 트리의 값이 모두 없다면 같은 트리기 때문에 True
2. 둘 중에 하나의 값이 없거나 val이 다를 경우 False
3. root부터 sub Tree를 탐색해가는 방식인 1, 2를 계속해서 반복하면 된다.
생각보다 코드는 매우 간단하다.

구현코드
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: Optional[TreeNode]
:type q: Optional[TreeNode]
:rtype: bool
"""
if not q and not p:
return True
if not q or not p or p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
728x90
'코딩 테스트 > python(파이썬)' 카테고리의 다른 글
| LeetCode: Group Anagrams (0) | 2025.05.22 |
|---|---|
| LeetCode: Symmetric Tree (2) | 2025.05.06 |
| LeetCode: Kth Largest Element in a Stream (0) | 2025.05.06 |
| LeetCode: Relative Ranks (0) | 2025.05.06 |
| LeetCode: 3Sum (0) | 2025.05.05 |
Comments