
📖이 포스팅은 '파이썬 알고리즘 인터뷰 - 박상길님' 책을 보고 작성되었습니다.
😎문제 : https://leetcode.com/problems/invert-binary-tree/submissions/
중앙을 기준으로 이진 트리를 반전시키는 문제
[반복 구조로 BFS]
import collections
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
queue = collections.deque([root])
while queue:
node = queue.popleft()
if node:
node.left, node.right = node.right, node.left
queue.append(node.left)
queue.append(node.right)
return root
- 부모 노드부터 스왑하며 계속 아래로 내려가는 하향(Top-Down)방식이다.
[반복 구조로 DFS - stack]
import collections
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
stack = collections.deque([root])
while stack:
node = stack.pop()
if node:
node.left, node.right = node.right, node.left
stack.append(node.left)
stack.append(node.right)
return root
[가장 파이썬 다운 방식]
import collections
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root:
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
'자료구조와 알고리즘 > 🥑알고리즘' 카테고리의 다른 글
[알고리즘][트리] - 5. 두 이진 트리 병합 (0) | 2022.06.20 |
---|---|
[알고리즘][트리] - 3. 가장 긴 동일 값의 경로 (0) | 2022.06.02 |
[알고리즘][트리] - 2. 이진 트리의 직경 (0) | 2022.04.26 |
[알고리즘][트리] - 1. 이진 트리의 최대 깊이 (0) | 2022.04.18 |
[알고리즘][최단 거리] - 2.k 경유지 내 가장 저렴한 항공권 (0) | 2022.04.08 |