Back to Leetcode Go

226. Invert Binary Tree

website/content.en/ChapterFour/0200~0299/0226.Invert-Binary-Tree.md

1.7.971.1 KB
Original Source

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

go

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
}