Given the root of a binary tree, invert the tree, and return its root.
이진 트리의 루트가 주어졌을때 역순으로 바꿔 리턴하는 문제
https://leetcode.com/problems/invert-binary-tree/description/
Example 1:

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Example 2:

Input: root = [2,1,3]
Output: [2,3,1]
Example 3:
Input: root = []
Output: []
재귀를 통해 쉽게 풀 수 있는 문제
1. 루트 노드의 왼쪽 오른쪽 노드를 바꾼다
2. 재귀를 통해 왼쪽 오른쪽 노드로 들어가서 반복한다
class Solution:
def invertTree(self, root: 'TreeNode') -> 'TreeNode':
if not root:
return root
else:
# 왼쪽 오른쪽 Child Node 바꾸기
root.left, root.right = root.right, root.left
self.invertTree(root.left) # 한단계 아래로 재귀
self.invertTree(root.right)
return root
트리의 기본적인 문제라서 금방 풀 수 있었던것 같다

반응형
'알고리즘 & 자료구조 > Leetcode' 카테고리의 다른 글
| [Leetcode 543] - Diameter of Binary Tree w/ Python (0) | 2024.04.09 |
|---|---|
| [Leetcode 104] - Maximum Depth of Binary Tree w/ Python (0) | 2024.04.08 |
| [Leetcode 25] - Reverse Nodes in k-Group w/ Python (0) | 2024.04.08 |
| [Leetcode 23] - Merge k Sorted Lists w/ Python (0) | 2024.04.08 |
| [Leetcode 146] - LRU Cache w/ Python (0) | 2024.04.07 |