Given the root
of a binary tree, invert the tree, and return its root.
For example:
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Input: root = [2,1,3]
Output: [2,3,1]
Input: root = []
Output: []
Constraints:
[0, 100]
.-100 <= Node.val <= 100
Could you provide an algorithm to invert the binary tree? Explain the time and space complexity. Can you handle edge cases, such as an empty tree?
When 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:
The brute force approach to inverting a binary tree involves examining every single node. For each node, we simply swap its left and right children. This process ensures the entire tree is inverted by exhaustively considering each node's arrangement.
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
To invert a binary tree, we want to swap the left and right children of every node in the tree. The process is recursive, meaning we'll apply the same logic to smaller parts of the tree until the entire tree is inverted. We essentially visit each node and swap its children.
Here's how the algorithm would work step-by-step:
def invert_binary_tree(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(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; an empty tree inverted is still an empty tree. |
Tree with only one node (root with no children) | Return the root node itself as it is already considered inverted. |
Completely unbalanced or skewed tree (all nodes on one side) | Recursive or iterative approaches should handle this without stack overflow given sufficient resources, but watch for very deep recursion. |
Perfectly balanced tree | Standard recursive or iterative approaches should efficiently invert this type of tree. |
Tree with duplicate values | The inversion process is based on structure, not data values, so duplicates have no impact. |
Very large tree (potential stack overflow with recursion) | Consider an iterative approach using a stack or queue to avoid exceeding recursion depth limits. |
Tree with negative values | The value of the nodes does not impact tree inversion; no special handling is required. |
Root having only a left or right child. | The algorithm should still correctly swap the single child to the other side and continue the traversal. |