Invert Binary Tree
To solve this coding challenge of inverting a binary tree, we need to recursively swap the left and right child nodes of each node in the tree. This process involves traversing the tree, swapping the children at each node, and recursively applying this operation to both subtrees.
# Explanation
A binary tree is a data structure where each node has at most two children referred to as the left child and the right child. Inverting a binary tree means swapping each node's left and right children throughout the entire tree.Steps Involved:
-
Base Case
: To handle the scenario where the node is
None
None
- Swap Operation : Swap the left child and the right child of the current node.
- Recursive Call : Recursively call the invert function for the (swapped) left subtree and the right subtree.
- Return the root : After all swaps and recursive calls are done, return the current node (root of the subtree being processed). To illustrate the detailed steps, here is a pseudocode with comments for clarity:
-
Function Definition
: The function
invertBinaryTree
node
-
Base Case Check
: Check if the
node
None
None
None
-
Swapping Children
: Use a temporary variable to hold one of the children while swapping to ensure no data is lost. We assign
node.left
temp
node.left
node.right
node.right
temp
-
Recursive Calls for Subtrees
: Call
invertBinaryTree
node.left
node.right
- Return the Node : Finally, return the node so that the inversion is maintained throughout the recursive calls.
Pseudocode
# Define a function to invert a binary tree given its root node
function invertBinaryTree(node):
# Base case: if the node is None, return None
if node is None:
return None
# Swap the left and right child nodes
temp = node.left # store the left child in a temporary variable
node.left = node.right # assign the right child to the left child
node.right = temp # assign the stored left child to the right child
# Recursively call the function on the left subtree
invertBinaryTree(node.left)
# Recursively call the function on the right subtree
invertBinaryTree(node.right)
# Return the current node (root of the subtree)
return node
Step-by-Step Explanation / Detailed Steps in Pseudocode
Complexity Analysis
- Time Complexity : The function visits each node exactly once; hence, the time complexity is O(n), where n is the number of nodes in the tree.
- Space Complexity : The space complexity is O(h), where h is the height of the tree, due to the recursive call stack. In the worst case of a completely unbalanced tree, this could be O(n).