Open In App

Inverting a Binary Tree in JavaScript

Last Updated : 31 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

One can Invert a binary tree using JavaScript. Inverting a binary tree, also known as mirroring a binary tree, is the process of swapping the left and right children of all nodes in the tree. Below is the diagram to understand the problem clearly

invert_tree
Inverting a binary tree

Below are the approaches to invert a binary tree in JavaScript:

Using Iterative Approach (DFS)

If the root is null, return null. Create a stack and push the root node onto it. This stack will help in performing a depth-first traversal (DFS) of the tree. While the stack is not empty, continue processing nodes. Pop a node from the stack to work on it. Swap the left and right children of this node. Push the left and right children (if they exist) onto the stack to process them later. Return the root node when entire tree has been processed.

Example : To demonstrate Inverting of a binary tree using Iterative Approach using stack.

JavaScript
class TreeNode 
{
    constructor(value = 0, left = null, right = null)
    {
        this.value = value;
        this.left = left;
        this.right = right;
    }
}

function invertBT(root)
{
    if (root === null) 
    {
        return null;
    }

    const stack = [root];

    while (stack.length > 0) 
    {
        const current = stack.pop();

        // Swap the left and right children
        [current.left, current.right] = [current.right, current.left];

        // Add children to the 
        // stack to process them later
        if (current.left !== null) {
            stack.push(current.left);
        }
        if (current.right !== null) {
            stack.push(current.right);
        }
    }

    return root;
}
function printTree(root) {
    if (root === null) {
        return "Tree is empty";
    }

    const queue = [root];
    const result = [];

    while (queue.length > 0) {
        const current = queue.shift();
        result.push(current.value);

        if (current.left !== null) 
        {
            queue.push(current.left);
        }
        if (current.right !== null)
        {
            queue.push(current.right);
        }
    }

    return result.join(' ');
}
const 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);

console.log("Original Tree:");
console.log(printTree(root));

// Invert the tree using the 
// iterative stack approach (DFS)
const invertedRoot = invertBT(root);

console.log("Inverted Tree:");
console.log(printTree(invertedRoot));

Output
Original Tree:
4 2 7 1 3 6 9
Inverted Tree:
4 7 2 9 6 3 1

Time Complexity: O(n)

Space Complexity: O(n)

Using Recursive Approach

If the root is null, return null. For the current node, swap its left and right children. Call the invertTree function recursively on the left child. Call the invertTree function recursively on the right child. After inverting its children, return the current node.

Example : To demonstrate Inverting of a binary tree using recursion in JavaScript.

JavaScript
class TreeNode {
    constructor(value = 0, left = null, right = null) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
}
function invertTree(root) {
    if (root === null) {
        return null;
    }

    // Swap the left and right children
    [root.left, root.right] = [root.right, root.left];

    // Recursively invert the left and right subtrees
    invertTree(root.left);
    invertTree(root.right);

    return root;
}
function printTree(root) {
    if (root === null) {
        return "Tree is empty";
    }

    const queue = [root];
    const result = [];

    while (queue.length > 0) {
        const current = queue.shift();
        result.push(current.value);

        if (current.left !== null) {
            queue.push(current.left);
        }
        if (current.right !== null) {
            queue.push(current.right);
        }
    }

    return result.join(' ');
}

const 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);

console.log("Original Tree:");
console.log(printTree(root));

// Invert the tree using recursive approach
const invertedRoot = invertTree(root);

console.log("Inverted Tree:");
console.log(printTree(invertedRoot));

Output
Original Tree:
4 2 7 1 3 6 9
Inverted Tree:
4 7 2 9 6 3 1

Time Complexity: O(n)

Space Complexity: O(n)

Using Level Order Traversal (BFS)

Level Order Traversal, also known as Breadth-First Search (BFS), can also be used to invert a binary tree. This approach uses a queue to process each level of the tree one at a time, swapping the left and right children of each node.

Explanation

  1. If the root is null, return null.
  2. Initialize a queue and enqueue the root node.
  3. While the queue is not empty:
    • Dequeue a node from the queue.
    • Swap its left and right children.
    • If the left child is not null, enqueue it.
    • If the right child is not null, enqueue it.
  4. Continue processing nodes until the queue is empty.
  5. Return the root node when the entire tree has been processed.

Example:

JavaScript
class TreeNode {
    constructor(value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
}

function invertTree(root) {
    if (root === null) {
        return null;
    }

    let queue = [];
    queue.push(root);

    while (queue.length > 0) {
        let current = queue.shift();

        // Swap the left and right children
        let temp = current.left;
        current.left = current.right;
        current.right = temp;

        // Enqueue left and right children
        if (current.left !== null) {
            queue.push(current.left);
        }
        if (current.right !== null) {
            queue.push(current.right);
        }
    }

    return root;
}

// Example usage
let 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);

console.log(invertTree(root))

Output
TreeNode {
  value: 4,
  left: TreeNode {
    value: 7,
    left: TreeNode { value: 9, left: null, right: null },
    right: TreeNode { value: 6, left: null, right: null }
  },
  right: TreeNode {
   ...



Next Article

Similar Reads