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:
[0, 100].-100 <= Node.val <= 100When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Inverting a binary tree means swapping the left and right children of every node in the tree. The brute force approach involves looking at each node individually and performing the swap.
Here's how the algorithm would work step-by-step:
def invert_binary_tree_brute_force(root):
if root is None:
return None
# Swap the left and right children of the current node.
root.left, root.right = root.right, root.left
# Recursively invert the left subtree.
invert_binary_tree_brute_force(root.left)
# Recursively invert the right subtree.
invert_binary_tree_brute_force(root.right)
return rootTo invert a binary tree, we aim to swap the left and right children of each node throughout the tree. We process the tree in a way that ensures we visit every part of the tree to perform this swap systematically. This approach avoids redundant operations and makes sure we touch every connection once.
Here's how the algorithm would work step-by-step:
def invert_binary_tree(root):
if root:
# Swap the left and right children of the current node.
root.left, root.right = root.right, root.left
# Recursively invert the left subtree.
invert_binary_tree(root.left)
# Recursively invert the right subtree.
invert_binary_tree(root.right)
return root| Case | How to Handle |
|---|---|
| Null or empty tree (root is null) | Return null immediately as there's nothing to invert. |
| Tree with only a root node (no left or right children) | Return the root node itself as it's already 'inverted'. |
| Skewed tree (e.g., all nodes only have left children) | The recursive calls will still proceed down the skewed branch, correctly inverting the tree structure. |
| Tree with duplicate values | Duplicate values do not affect the inversion logic; the structure is the only thing being modified. |
| Very large tree (potential stack overflow with recursion) | While recursion is the natural approach, consider iterative solution using a stack to avoid exceeding stack limits. |
| Tree with negative values | Negative values do not affect the inversion logic; node structure is being modified, not node values. |
| Perfectly balanced tree | The inversion logic applies correctly and efficiently to a perfectly balanced tree. |
| Integer overflow in node values (if applicable in other tree problems but good to check) | The values themselves are not modified during the inversion, so integer overflow is irrelevant in this specific problem. |