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.
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 left = invertTree(root.left);
10 const right = invertTree(root.right);
11 root.left = right;
12 root.right = left;
13 return root;
14}
This JavaScript solution defines a TreeNode function constructor and uses a recursive invertTree function that swaps the children 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.
1#include <iostream>
2#include <queue>
3
4struct TreeNode {
5 int val;
6 TreeNode *left;
7 TreeNode *right;
8 TreeNode(int x) : val(x), left(NULL), right(NULL) {}
9};
10
11TreeNode* invertTree(TreeNode* root) {
12 if (root == NULL) return NULL;
13 std::queue<TreeNode*> q;
14 q.push(root);
15 while (!q.empty()) {
16 TreeNode* current = q.front();
17 q.pop();
18 std::swap(current->left, current->right);
19 if (current->left) q.push(current->left);
20 if (current->right) q.push(current->right);
21 }
22 return root;
23}
The C++ solution uses the STL queue to perform an iterative breadth-first traversal. During each iteration, it swaps the left and right children of the current node and pushes them to the queue if they exist.