This problem involves recursively inverting a binary tree. The core idea is to process the tree level by level, swapping the left and right children of each node. The recursive approach elegantly handles this level-by-level inversion.
Algorithm:
Base Case: If the current node (root
) is null
or its left child is null
, it means we've reached the bottom of a subtree or the entire tree is empty or has only one node. In this case, we return the current node as the new root of the inverted subtree (or null
if the tree was empty).
Recursive Step: We recursively call upsideDownBinaryTree
on the left subtree (root.left
). This step ensures that the left subtree is inverted first. The result of this recursive call (newRoot
) becomes the new root of the inverted tree.
Rewiring: The crucial step is rewiring the nodes. We perform the following actions:
root.left.right = root
: The original root becomes the new right child of the inverted left subtree's root.root.left.left = root.right
: The original right child becomes the new left child of the inverted left subtree's root.root.left = None
: We set the original left child to null
to avoid cycles and maintain the correct tree structure.root.right = None
: We set the original right child to null
as it has already been rewired.Return: Finally, we return newRoot
, which is the root of the completely inverted subtree.
Time Complexity Analysis:
The time complexity is O(N), where N is the number of nodes in the tree. This is because each node is visited and processed exactly once during the recursive traversal.
Space Complexity Analysis:
The space complexity is O(H), where H is the height of the tree. This is due to the recursive call stack. In the worst case (a skewed tree), H could be equal to N, resulting in O(N) space complexity. In a balanced tree, H would be log₂N, leading to O(log₂N) space complexity.
Code Explanation (Python):
The Python code directly implements the algorithm described above. The TreeNode
class represents a node in the binary tree. The upsideDownBinaryTree
function performs the recursive inversion. The comments in the code clearly indicate the steps involved at each stage.
Code Explanation (Java, C++, Go):
The Java, C++, and Go code follow the same logic as the Python code, differing only in syntax. Each language's specific tree node structure is used (TreeNode
in Java and C++, and the similarly defined struct in Go). The core recursive algorithm and rewiring steps remain identical.
Example Usage (Python):
# Example usage:
root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))
inverted_root = Solution().upsideDownBinaryTree(root)
# Now inverted_root represents the inverted tree.