https://leetcode.com/problems/invert-binary-tree/description/
# Definition for a binary tree node.
from typing import Optional
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]:
def dfs(node):
if node is None:
return
node.left, node.right = node.right, node.left
dfs(node.left)
dfs(node.right)
return
dfs(root)
return root
leaf까지 left, right 스왑하면서 진행하면 된다.
파이썬 알고리즘 인터뷰 45번