0226. Invert Binary Tree

226. Invert Binary Tree #

Problem #

Invert a binary tree.

Example:

Input:


     4
   /   \
  2     7
 / \   / \
1   3 6   9

Output:


     4
   /   \
  7     2
 / \   / \
9   6 3   1

Trivia:

This problem was inspired by this original tweet by Max Howell:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.

Problem Summary #

The “classic” problem of inverting a binary tree.

Solution Approach #

Still use recursion to solve it: first recursively call to invert the left child of the root node, then recursively call to invert the right child of the root node, and then swap the left child and right child of the root node.

Code #


package leetcode

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func invertTree(root *TreeNode) *TreeNode {
	if root == nil {
		return nil
	}
	invertTree(root.Left)
	invertTree(root.Right)
	root.Left, root.Right = root.Right, root.Left
	return root
}


Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文