🧠
Iterative Approach Using Queue (BFS)
💡 This approach uses a queue to invert the tree level by level, which helps understand iterative tree traversal and avoids recursion stack issues.
Intuition
Use a queue to traverse the tree in breadth-first order, swapping children at each node as you go.
Algorithm
- If the root is null, return null.
- Initialize a queue and enqueue the root node.
- While the queue is not empty:
- Dequeue a node from the queue.
- Swap its left and right children.
- If left child is not null, enqueue it.
- If right child is not null, enqueue it.
- Return the root node.
💡 This approach uses level order traversal to visit nodes systematically and invert them without recursion.
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def invertTree(root):
if root is None:
return None
queue = deque([root])
while queue:
node = queue.popleft()
node.left, node.right = node.right, node.left
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return root
# Example usage:
# root = TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode(7, TreeNode(6), TreeNode(9)))
# inverted_root = invertTree(root)
Line Notes
from collections import dequeImport deque for efficient queue operations
if root is None:Handle empty tree edge case
queue = deque([root])Initialize queue with root node to start BFS
while queue:Process nodes until queue is empty
node = queue.popleft()Dequeue current node to process
node.left, node.right = node.right, node.leftSwap left and right children of current node
if node.left:If left child exists after swap, enqueue it for later processing
if node.right:If right child exists after swap, enqueue it for later processing
return rootReturn the root of the inverted tree
import java.util.LinkedList;
import java.util.Queue;
public class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
return root;
}
// Example usage:
// public static void main(String[] args) {
// TreeNode root = new TreeNode(4);
// root.left = new TreeNode(2);
// root.right = new TreeNode(7);
// root.left.left = new TreeNode(1);
// root.left.right = new TreeNode(3);
// root.right.left = new TreeNode(6);
// root.right.right = new TreeNode(9);
// Solution sol = new Solution();
// TreeNode inverted = sol.invertTree(root);
// }
}
Line Notes
if (root == null) return null;Handle empty tree case immediately
Queue<TreeNode> queue = new LinkedList<>();Initialize queue for BFS traversal
queue.add(root);Add root node to start BFS
while (!queue.isEmpty()) {Process nodes until queue is empty
TreeNode node = queue.poll();Dequeue current node
TreeNode temp = node.left;Temporarily store left child for swapping
node.left = node.right;Assign right child to left
node.right = temp;Assign stored left child to right
if (node.left != null) queue.add(node.left);Enqueue left child if exists
if (node.right != null) queue.add(node.right);Enqueue right child if exists
return root;Return root of inverted tree
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr) return nullptr;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
TreeNode* temp = node->left;
node->left = node->right;
node->right = temp;
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
return root;
}
// Example usage:
// int main() {
// TreeNode* root = new TreeNode(4);
// root->left = new TreeNode(2);
// root->right = new TreeNode(7);
// root->left->left = new TreeNode(1);
// root->left->right = new TreeNode(3);
// root->right->left = new TreeNode(6);
// root->right->right = new TreeNode(9);
// TreeNode* inverted = invertTree(root);
// return 0;
// }
Line Notes
if (root == nullptr) return nullptr;Handle empty tree case
queue<TreeNode*> q;Initialize queue for BFS
q.push(root);Start BFS with root node
while (!q.empty()) {Process nodes until queue is empty
TreeNode* node = q.front();Get current node from queue front
q.pop();Remove current node from queue
TreeNode* temp = node->left;Store left child temporarily for swapping
node->left = node->right;Assign right child to left
node->right = temp;Assign stored left child to right
if (node->left) q.push(node->left);Enqueue left child if exists
if (node->right) q.push(node->right);Enqueue right child if exists
return root;Return root of inverted tree
function TreeNode(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
function invertTree(root) {
if (root === null) return null;
const queue = [root];
while (queue.length > 0) {
const node = queue.shift();
[node.left, node.right] = [node.right, node.left];
if (node.left !== null) queue.push(node.left);
if (node.right !== null) queue.push(node.right);
}
return root;
}
// Example usage:
// const root = new TreeNode(4,
// new TreeNode(2, new TreeNode(1), new TreeNode(3)),
// new TreeNode(7, new TreeNode(6), new TreeNode(9))
// );
// const inverted = invertTree(root);
// console.log(inverted);
Line Notes
if (root === null) return null;Handle empty tree edge case
const queue = [root];Initialize queue with root node for BFS
while (queue.length > 0) {Process nodes until queue is empty
const node = queue.shift();Dequeue node from front of queue
[node.left, node.right] = [node.right, node.left];Swap left and right children using destructuring
if (node.left !== null) queue.push(node.left);Enqueue left child if exists
if (node.right !== null) queue.push(node.right);Enqueue right child if exists
return root;Return root of inverted tree
Each node is visited once, so time is O(n). The queue can hold up to O(n) nodes in the worst case (e.g., a full level).
💡 For a tree with 1000 nodes, this means about 1000 operations and queue size up to 1000 in worst case, which is manageable.
Interview Verdict: Accepted
This iterative approach is also accepted and useful when recursion depth is a concern.