![見出し画像](https://assets.st-note.com/production/uploads/images/84404747/rectangle_large_type_2_9d7b406ad80dd7a30b7f587c0b421196.png?width=1200)
Photo by
emitochio
ほぼ日刊競プロ leetcode 226. Invert Binary Tree
226. Invert Binary Tree
Given the root of a binary tree, invert the tree, and return its 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 not root:
return None
ans = TreeNode(root.val)
ans.right = self.invertTree(root.left)
ans.left = self.invertTree(root.right)
return ans