Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- Array
- tree
- dfs
- Depth-first Search
- hash table
- two pointers
- 미디움
- backtracking
- Binary
- 쉬움
- 중간
- HashTable
- recursive
- 리트코드
- binary tree
- linked list
- math
- DP
- leetcode
- easy
- 재귀
- binary search
- 이진트리
- string
- list
- Medium
- matrix
- sorting
- Python
- 문자열
Archives
- Today
- Total
부부의 코딩 성장 일기
LeetCode 226(Invert Binary Tree, Python) 본문
1. 문제 링크
LeetCode - The World's Leading Online Programming Learning Platform
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
2. 문제 설명
- binary tree의 root가 주어졌을 때, 이를 invert한 root를 반환
- 예시) input이 [4,2,7,1,3,6,9] 이면 output이 [4,7,2,9,6,3,1]로 각 노드의 왼쪽과 오른쪽을 바꾼 root를 반환
3. 처음 풀이
- 결국 재귀를 써서, root.right를 root.left에, root.left를 root.right에 두는 것을 반복
- TreeNode(root.val, self.invertTree(root.right), self.invertTree(root.left))
- 기본 로직으로 root가 None이면 root 반환
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return root
return TreeNode(root.val, self.invertTree(root.right), self.invertTree(root.left))
4. 다른 풀이
- 거의 대부분의 풀이가 위의 방식처럼 작성되어 있었다.
- runtime 가장 빠른 코드로 보니, 거의 비슷하다. 아래풀이가 약간 다른 풀이
- 처음 풀이의 경우, 새로운 노드를 생성하고, 왼쪽 서브트리와 오른쪽 서브트리를 반전하는 형태로 짰다면,
- 아래는 주어진 노드의 왼쪽과 오른쪽 서브트리를 직접 교환하는 방식으로 작성이 되어있음.
- 아래의 코드가 추가적인 노드 생성 없이 직접 노드 값을 교환하므로 메모리 사용이 효율적
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
temp = root.left
root.left = root.right
root.right = temp
self.invertTree(root.left)
self.invertTree(root.right)
return root
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 225(Implement Stack using Queues) (0) | 2024.02.13 |
---|---|
LeetCode 228(Summary Ranges, Python) (0) | 2024.02.11 |
LeetCode 222(Count Complete Tree Nodes, Python) (0) | 2024.02.09 |
LeetCode 96(Unique Binary Search Trees, Python) (0) | 2024.02.08 |
LeetCode 95(Unique Binary Search Trees II, Python) (1) | 2024.02.07 |