Java: Invert Binary Tree

Thought Process

The Invert Binary Tree problem requires swapping the left and right children of every node in the tree. Here are two approaches:

Approach 1: Recursive Approach - Use a recursive function to traverse the tree. Swap the left and right children of each node recursively.

Approach 2: Iterative Approach (BFS) - Use a queue to perform a level-order traversal (BFS) of the tree. Swap the left and right children of each node during traversal. This approach avoids recursion and uses explicit memory for traversal.

Approach 1: Recursive Approach

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
 
class Solution {
    
    public TreeNode invertTree(TreeNode root) {

        if(root==null)
            return root;

        if(root.left == null && root.right==null)
            return root;

        TreeNode tmp = invertTree(root.left);
        root.left = invertTree(root.right);
        root.right = tmp;

        return root;
    }
}

Approach 2: Iterative Approach (BFS)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {

    public TreeNode invertTree(TreeNode root) {

        if(root==null)
            return root;

        if(root.left==null && root.right==null)
            return root;

        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);

        while(!q.isEmpty()){

            TreeNode nod = q.poll();

            if(nod.left!=null)
                q.offer(nod.left);
            
            if(nod.right!=null)
                q.offer(nod.right);

            TreeNode tmp = nod.left;
            nod.left = nod.right;
            nod.right = tmp;
        }
        return root;
    }
}

Code Complexity

Time Complexity: O(n)

Both approaches visit each node exactly once, ensuring linear time complexity.

Space Complexity: O(n)

The recursive approach uses O(h) space for the call stack, where h is the height of the tree. The iterative approach uses O(n) space for the queue in the worst case, where 'n' is the number of nodes in the tree.

Code copied!