Recursive DFS
Intuition
The recursive approach is the most elegant way to invert a binary tree. For each node, we simply swap its left and right children, then recursively invert each subtree. The base case is a null node, which we return as-is. The recursion naturally handles all nodes in the tree, and after every subtree has been inverted, the entire tree is inverted. The order of operations (swap then recurse, or recurse then swap) does not matter since both produce the correct result.
Algorithm
- If the root is null, return null (base case).
- Swap the left and right children of the current node.
- Recursively invert the left subtree.
- Recursively invert the right subtree.
- Return the root.
O(n)SpaceO(h) where h is the height of the treeCode (C++ · Java · Python · Go)
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr) return nullptr;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}def invertTree(root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
root.left, root.right = root.right, root.left
invertTree(root.left)
invertTree(root.right)
return rootfunc invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
root.Left, root.Right = root.Right, root.Left
invertTree(root.Left)
invertTree(root.Right)
return root
}