Invert Binary Tree - Complete Solution Guide
Invert Binary Tree is LeetCode problem 226, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
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
Detailed Explanation
The problem asks you to invert a given binary tree. Inverting a binary tree means swapping the left and right children of every node in the tree. The input is the root node of the binary tree, and the output is the root node of the inverted binary tree. The input can be an empty tree (represented by `null` or `None`), a single node, or a tree with multiple nodes. Constraints limit the number of nodes and the range of node values.
Solution Approach
The provided solutions use a recursive approach. The `invertTree` function takes the root of the tree as input. If the root is `null` (or `None`), it means the tree is empty, so it returns `null`. Otherwise, it recursively inverts the left and right subtrees, then swaps the left and right children of the current node. The swapped children, which are now the inverted subtrees, are assigned back to the left and right of the current node, and the inverted root is returned.
Step-by-Step Algorithm
- Step 1: Check if the root node is `null` (or `None`). If it is, return `null` (or `None`) because an empty tree is already inverted.
- Step 2: Recursively call `invertTree` on the left subtree and assign the result to a temporary variable (or directly swap in-place).
- Step 3: Recursively call `invertTree` on the right subtree and assign the result to another temporary variable (or directly swap in-place).
- Step 4: Swap the left and right children of the current node using simultaneous assignment (e.g., `root.left, root.right = root.right, root.left`).
- Step 5: Return the modified root node.
Key Insights
- Insight 1: Recursive approach is ideal for traversing and manipulating a tree's structure. The problem naturally lends itself to recursion because inverting a subtree is independent of inverting other subtrees.
- Insight 2: The base case for the recursion is an empty subtree (null or None). When a subtree is empty, nothing needs to be inverted, and the function can simply return.
- Insight 3: The order of swapping left and right children and the recursive calls is crucial. Swapping them first ensures the correct inversion; recursive calls happen *after* the swap.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(h)
Topics
This problem involves: Tree, Depth-First Search, Breadth-First Search, Binary Tree.
Companies
Asked at: Oracle, Ozon.