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로도 풀이해봐야겠다.