226. Invert Binary Tree


問題の説明


Given the root of a binary tree, invert the tree, and return its root.
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

こうそくじょうけん

The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100

完全なコード

from collections import deque
# 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 bfs(self,current):
        queue=deque([current])
        
        while queue:
            node=queue.popleft()
            
            if node:
                node.left,node.right=node.right,node.left
                
                queue.append(node.left)
                queue.append(node.right)
        
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        self.bfs(root)
        return root

に感銘を与える


基本的な問題ですが、これは再解決しなければならない問題です.BFSだけでなくDFSで説明します.