This approach employs recursion to invert the binary tree. The basic idea is to traverse the tree and swap the left and right children of every node recursively. We recursively call the function on the left and right subtrees until we reach the base case, which is when the node is null.
Time Complexity: O(n) where n is the number of nodes in the tree, because each node is visited once.
Space Complexity: O(h) where h is the height of the tree, for the recursion stack.
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7class Solution:
8 def invertTree(self, root: TreeNode) -> TreeNode:
9 if root is None:
10 return None
11 left = self.invertTree(root.left)
12 right = self.invertTree(root.right)
13 root.left = right
14 root.right = left
15 return root
The Python solution uses a TreeNode class for node definition and a recursive method within a Solution class to inverse the tree recursively by swapping the nodes.
The iterative approach involves using a queue or stack to traverse the tree level by level (or depth by depth) while inverting the child nodes by putting the left child in place of the right child and vice versa for each node. This is effectively a breadth-first traversal that swaps children iteratively.
Time Complexity: O(n) where n is the number of nodes in the tree.
Space Complexity: O(n) due to the queue data structure.
1function TreeNode(val, left = null, right = null) {
2 this.val = val;
3 this.left = left;
4 this.right = right;
5}
6
7function invertTree(root) {
8 if (root === null) return null;
9 const queue = [];
10 queue.push(root);
11 while (queue.length > 0) {
12 const current = queue.shift();
13 [current.left, current.right] = [current.right, current.left];
14 if (current.left !== null) queue.push(current.left);
15 if (current.right !== null) queue.push(current.right);
16 }
17 return root;
18}
This solution in JavaScript uses a simple queue-based iteration using an array as the queue. Each node is processed by popping elements from the front and swapping children.