心路历程:
翻转一瞬间没什么思路,其实就是挨个把每个结点的左右子树都翻转了。主要不要按照左右子树去思考,要按照结点去思考。
翻转既可以从上到下翻转(前序遍历),也可以从下到上翻转(后序遍历)
每一层翻转只需要交换左右子树的赋值即可
解法: 递归
# 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]:def dfs(node):if not node: returnnode.left, node.right = node.right, node.leftdfs(node.left)dfs(node.right)dfs(root)return root