The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100
Solutions
Solution 1: Recursion
The idea of recursion is very simple, which is to swap the left and right subtrees of the current node, and then recursively swap the left and right subtrees of the current node.
The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the binary tree.
1 2 3 4 5 6 7 8 91011121314151617
# 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 = rightclassSolution:definvertTree(self,root:Optional[TreeNode])->Optional[TreeNode]:defdfs(root):ifrootisNone:returnroot.left,root.right=root.right,root.leftdfs(root.left)dfs(root.right)dfs(root)returnroot
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcinvertTree(root*TreeNode)*TreeNode{vardfsfunc(*TreeNode)dfs=func(root*TreeNode){ifroot==nil{return}root.Left,root.Right=root.Right,root.Leftdfs(root.Left)dfs(root.Right)}dfs(root)returnroot}