← All solutionsInvert Binary Tree
May 31, 2025 • Go •binary tree, depth first search • easy
Problem
- Given the root of a binary tree, invert the tree and return its root.
Approach
- 1. dfs to leaf nodes and swap left and right children all the way back up.
Go Solution
func invertTree(root *treenode) *treenode {
var dfs func(root *treenode)
dfs = func(node *treenode) {
if node == nil {
return
}
dfs(node.left)
dfs(node.right)
node.left, node.right = node.right, node.left
}
dfs(root)
return root
}
LeetCode Problem Link