Leetcode 226: Invert Binary Tree

grid47
grid47
Exploring patterns and algorithms
Oct 15, 2024 4 min read

A tree slowly flipping upside down, with nodes glowing as they invert.
Solution to LeetCode 226: Invert Binary Tree Problem

Given the root of a binary tree, invert the tree by swapping the left and right subtrees of every node, and return its root.
Problem
Approach
Steps
Complexity
Input: The input is the root of a binary tree, where each node contains an integer value and references to its left and right children.
Example: Input: root = [3,1,4,null,2,null,5]
Constraints:
• The number of nodes in the tree is in the range [0, 100].
• -100 <= Node.val <= 100
Output: The output is the root of the inverted binary tree, where the left and right subtrees of every node are swapped.
Example: Output: [3,4,1,5,null,null,2]
Constraints:
• The structure of the tree must maintain binary tree properties during inversion.
Goal: Swap the left and right subtrees recursively for every node in the binary tree.
Steps:
• Base Case: If the current node is null, return null.
• Recursively invert the left subtree.
• Recursively invert the right subtree.
• Swap the left and right children of the current node.
• Return the root node.
Goal: The problem is subject to the following constraints:
Steps:
• The binary tree can contain up to 100 nodes.
• Each node value is an integer in the range [-100, 100].
Assumptions:
• The input tree is well-formed and adheres to binary tree properties.
• Node values can include negative integers.
Input: Input: root = [5,3,8,1,4,7,9]
Explanation: The tree is inverted by swapping the left and right children of each node. Output: [5,8,3,9,7,4,1]

Input: Input: root = []
Explanation: An empty tree remains empty after inversion. Output: []

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus