Inverting a Binary Tree in JavaScript
Last Updated :
31 Jul, 2024
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
Inverting a binary treeBelow 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));
OutputOriginal 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));
OutputOriginal 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
- 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 the left child is not null, enqueue it.
- If the right child is not null, enqueue it.
- Continue processing nodes until the queue is empty.
- 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))
OutputTreeNode {
value: 4,
left: TreeNode {
value: 7,
left: TreeNode { value: 9, left: null, right: null },
right: TreeNode { value: 6, left: null, right: null }
},
right: TreeNode {
...
Similar Reads
Binary Search In JavaScript
Binary Search is a searching technique that works on the Divide and Conquer approach. It is used to search for any element in a sorted array. Compared with linear, binary search is much faster with a Time Complexity of O(logN), whereas linear search works in O(N) time complexity Examples: Input : ar
3 min read
Convert a Binary Tree to a Binary Search Tree using JavaScript
Given a Binary Tree, the task is to convert it to a Binary Search Tree. The conversion must be done in such a way that it keeps the original structure of the Binary Tree. Example: To demonstrate the conversion of the Binary Tree to the Binary Search Tree. Input: 10 / \ 2 7 / \ 8 4Output: 8 / \ 4 10
2 min read
Implementation of Binary Search Tree in Javascript
In this article, we would be implementing the Binary Search Tree data structure in Javascript. A tree is a collection of nodes connected by some edges. A tree is a non linear data structure. A Binary Search tree is a binary tree in which nodes that have lesser value are stored on the left while the
9 min read
Build Tree Array from JSON in JavaScript
Building a tree array from JSON in JavaScript involves converting a JSON object representing a hierarchical structure into an array that reflects the parent-child relationships. This tree array can be useful for various purposes like rendering hierarchical data in UI components performing tree-based
3 min read
Build Tree Array from Flat Array in JavaScript
To convert a flat array of comments into a tree-like structure using JavaScript. This technique is particularly useful when you need to render nested comments or any other hierarchical data in your web application. We will write a function called buildCommentsTree that takes the flat array of commen
7 min read
How to traverse 2D arrays in JavaScript?
A two-dimensional array or simply 2D array is a format to store data in a grid format that is rows and columns format. There is no special way of declaring a 2D array in JavaScript, we can simply pass an array as an element inside another array. the array obtained in this method will be created as a
6 min read
Binary Search Tree In Python
A Binary search tree is a binary tree where the values of the left sub-tree are less than the root node and the values of the right sub-tree are greater than the value of the root node. In this article, we will discuss the binary search tree in Python. What is a Binary Search Tree(BST)?A Binary Sear
11 min read
Find the Sum of All Left Leaves in a Given Binary Tree using JavaScript
Given a Binary Tree, find the sum of all left leaves in it. A binary tree is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. Finding the sum of all left leaves involves traversing the entire binary tree and checking each n
4 min read
Introduction to Degenerate Binary Tree
Every non-leaf node has just one child in a binary tree known as a Degenerate Binary tree. The tree effectively transforms into a linked list as a result, with each node linking to its single child. When a straightforward and effective data structure is required, degenerate binary trees, a special c
8 min read
How to insert a node in Binary Search Tree using Iteration
You are given a binary search tree (BST) and a value to insert into the tree. Print inorder traversal of the BST after the insertion.Example: Input:To the given BST insert 40 Output: Explanation:The new node 40 is a leaf node. Start searching from the root till a leaf node is hit, i.e while searchin
10 min read