
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