FrontendInterviews.dev

Loading problem…

295. Invert Binary Tree

Easy•
Acceptance: 85.71%
•
🔓3/3 Pro unlocks today

Given the root of a binary tree, invert the tree, and return its root.

Inverting a binary tree means swapping every left child with its corresponding right child, at every level of the tree.

This is the famous "Homebrew" problem — the one that inspired the tweet "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."

Requirements

1. Basic Functionality

  • Swap left and right children of every node
  • Return the root of the inverted tree
  • Handle null/empty trees

Example Usage

// Input:  [4,2,7,1,3,6,9]
// Output: [4,7,2,9,6,3,1]
//
//     4              4
//    / \            / \
//   2   7   →     7   2
//  / \ / \       / \ / \
// 1  3 6  9     9  6 3  1

Real-World Context

  • Mirror layouts: Creating RTL (right-to-left) versions of tree-based UI layouts
  • Image processing: Horizontal flip operations on quad-trees
  • Data transformation: Reversing hierarchical data structures

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100