| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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
- 파이썬
- populating next right pointers in each node
- 코테
- 정렬
- lgb
- 27448
- T tree
- 2247
- 코딩테스트
- C
- 힙 정렬
- dp
- 샤논 엔트로피
- 아니메컵
- 다이나믹 프로그래밍
- 코복장
- 17070
- ps
- 코딩
- 백준
- 정답코드
- 구현
- 실질적 약수
- dfs
- 딥러닝
- 부분수열의 합2
- 모두의 꿈
- BFS
- python
- 스펨메일 분류
Archives
- Today
- Total
코딩복습장
LeetCode: Symmetric Tree 본문
728x90
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:

Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:

Input: root = [1,2,2,null,3,null,3]
Output: false
Constraints:
- The number of nodes in the tree is in the range [1, 1000].
- -100 <= Node.val <= 100
Follow up: Could you solve it both recursively and iteratively?
이 문제는 root만을 기준으로 좌우가 대칭인지 살펴보는 문제이다.
문제푸는 방식은 다음과 같다.
root를 기준으로 오른쪽과 왼쪽 노드가 존재하지 않는다면 True를 반환한다.
root가 없어도 True를 반환한다.
이후 값이 같고 재귀의 방식으로 오른쪽 노드의 오른쪽과 왼쪽 노드의 왼쪽, 왼쪽노드의 오른쪽과 오른쪽 노드의 오른쪽 노드를 같은 함수의 parameter로 집어 넣는다. 이 값이 return값이 된다.
(값이 같은지 확인 + 대칭인지 확인)
이 과정을 반복하면 root를 기준으로 트리가 대칭인지 확인할 수 있게 된다!
생각하는데 시간이 굉장히 오래걸렸다.. 이런..


구현코드
# 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 isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def isMirror(t1, t2):
if not t1 and not t2:
return True
if not t1 or not t2:
return False
return (t1.val == t2.val and
isMirror(t1.left, t2.right) and
isMirror(t1.right, t2.left))
return isMirror(root.left, root.right) if root else True728x90
'코딩 테스트 > python(파이썬)' 카테고리의 다른 글
| LeetCode: Merge Intervals (0) | 2025.05.23 |
|---|---|
| LeetCode: Group Anagrams (0) | 2025.05.22 |
| LeetCode: SameTree (0) | 2025.05.06 |
| LeetCode: Kth Largest Element in a Stream (0) | 2025.05.06 |
| LeetCode: Relative Ranks (0) | 2025.05.06 |
Comments