226. Invert Binary Tree

Invert Binary Tree (LeetCode 226) is a Easy Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Tree Traversal Patterns (DFS & BFS) pattern, in the Recursive Preorder Traversal subpattern.

How to solve Invert Binary Tree

Invert Binary Tree is a Preorder Traversal problem, part of Tree Traversal Patterns (DFS & BFS). Master preorder traversal for tree construction, inversion, and path problems. Visit root before children.

Work towards the solution in these steps:

  1. Think about how tree traversal methods like DFS or BFS can help you visit every node in the tree.
  2. Using a recursive approach, consider how you can process each node before or after visiting its children.
  3. At each node, what simple operation can you perform to invert the tree structure locally?

The reference solution runs in O(n) time and O(h) space.

The Invert Binary Tree solution and editorial walks through the full approach with reference code.

Problem statement

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

Example 1:

Input: root = [4,2,7,1,3,6,9] Output: [4,7,2,9,6,3,1]

Example 2:

Input: root = [2,1,3] Output: [2,3,1]

Example 3:

Input: root = [] Output: []

Constraints:

- The number of nodes in the tree is in the range [0, 100].

- -100 <= Node.val <= 100

Topics and companies

Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree.

Reported in interviews at Microsoft, Amazon, Google, Facebook, eBay, Paypal.

How to practise Invert Binary Tree on Thita.ai

Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(n) time and O(h) space.

Open Invert Binary Tree in the code editor, or read the Invert Binary Tree editorial for a worked solution with its approach and complexity analysis.

Where Invert Binary Tree sits in the DSA pattern sheet

Problems related to Invert Binary Tree

Other problems that use the same Recursive Preorder Traversal and Tree Traversal Patterns (DFS & BFS) techniques:

Invert Binary Tree FAQ

What is the LeetCode number of Invert Binary Tree?

Invert Binary Tree is LeetCode problem 226, rated Easy.

What pattern is used to solve Invert Binary Tree?

Invert Binary Tree is a Preorder Traversal problem. It belongs to the Tree Traversal Patterns (DFS & BFS) pattern, in the Recursive Preorder Traversal subpattern.

What is the time complexity of Invert Binary Tree?

The reference solution runs in O(n) time and O(h) space.

Which companies ask Invert Binary Tree?

Invert Binary Tree has been reported in interviews at Microsoft, Amazon, Google, Facebook, eBay, Paypal.

Preparing this workspace.