- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Inverting a binary tree in JavaScript

The problem statement asks the user that given a binary tree , you need to find the mirror image of the elements of the binary tree such that reverse the corresponding and parallel siblings of the tree branches . In short, invert the whole binary tree given the original binary tree as an input.

The output of the problem statement looks like a reverse function of the input binary tree as the summary to implement for.

## What is a Tree in JavaScript

A tree refers to one of the optimized data structures to hold data where the data points present in the tree are called nodes of it. The tree data structure automatically visualizes like a tree in the real world . The top data point of the tree is called root node , and the branches coming out of the tree just like a real world tree are called child nodes which can also have recursive branches coming out of it having children or no children of it as well.

A tree data structure has no restriction of branches called child nodes coming out of a single node but there are many types of tree that exist in the data structure tree itself.

## What is a Binary Tree in JavaScript

Binary tree is a type of tree in Javascript where every branch of a tree contains at most two children only . It is also chronologically ordered where the left of the tree has lesser values than the root node and the right of the tree has greater values than the root node balancing the tree fully.

## What is a Inverted Binary Tree in JavaScript

The Inverted Binary Tree means inversion of a tree taking in particular rules where the left child of the binary tree becomes the right child of the binary tree. And this specific condition applies for recursive sub branches of trees.

## Algorithm - Create a Node

The algorithm to create a node in Binary Search Tree is as follows -

**Step 1**: Declare a class with name Node that takes in a constructor function with value parametre i.e. actual data point inside it.

**Step 2** : The constructor function will initialize the actual data point using this in javascript to the current context and reference whereas initializes left and right pointers to null as well for left and right places where the data point can be inserted in a tree. cCode for Algorithm -

## Code for Algorithm - Create a Node

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

## Algorithm - Print the Tree

The algorithm to display the node to the user after it is created using the createNode function , it returns all values present in the given node.

**Step 1** : Declare a function printTree that takes root value as its parameters provided by the user as a core input.

**Step 2** : Declare a list and queue of tree elements such that initialize the list with an empty array and queue with the root passed in as the parameter to the function.

**Step 3** : Till the length of the queue is not less than 0 , we need to shift the first element at the 0th index and push it back in the list of elements using the push method in javascript.

**Step 4** : It is a recursive step of the algorithm to check if the left sub branch of the tree is not null ,then push the left sub branch elements in the list .

**Step 5** : It is a recursive step of the algorithm to check if the right sub branch of the tree is not null ,then push the right sub branch elements in the list .

## Code for Algorithm - Print the Tree

const printTree = (root) => { let listOfTreeElements = []; let queueOfTreeElements = [root]; while (queueOfTreeElements.length) { let currentNode = queueOfTreeElements.shift(); listOfTreeElements.push(currentNode.value); if(currentNode.left) queueOfTreeElements.push(currentNode.left); if(currentNode.right) queueOfTreeElements.push(currentNode.right); } return listOfTreeElements; }

Now is the time to call the functions to perform some specific tasks of creating a node and using the printTree algorithm to display the nodes in the shape of a binary tree.

The new object will be created from the class declared as Node and values are inserted to the left and right sub branches.

### Example

let originalTree = new Node(4); originalTree.left = new Node(2); originalTree.right = new Node(7); originalTree.left.left = new Node(1); originalTree.left.right = new Node(3); originalTree.right.left = new Node(9); originalTree.right.right = new Node(0); console.log(printTree(originalTree));

The output of the binary search tree looks like after insertion of data points is :

### Output

Binary Search Tree after insertion : [ 4, 2, 7, 1, 3, 9, 0 ]

## Algorithm - findInvertedBinaryTree Method

**Step 1** : Declare a function with the name findInvertedBinaryTree that takes root value as a parameter.

**Step 2** : As the following function declared in Step 1 is a recursive function , it chooses a basecase for itself such that if root value equals to null , it returns back simply stating there is no tree available in the output .

**Step 3** : Traverse the left and right sub branches till you get the leaf nodes equal to null using recursive calling of the same function but with its left and right branches.

**Step 4** : Perform a swapping sub algorithm for the binary tree generated by the user through a temporaryHold variable that helps in swapping the left sub branch data point with right sub branch data point through bottom up approach going from bottom to the root value swapping all the left and child elements in sub branches of the tree present until you reaches the root which will be swapped by itself only.

## Code for Algorithm - findInvertedBinaryTree Method

function findInvertedBinaryTree (root) { if (root === null) return; let temporaryHold; findInvertedBinaryTree(root.left); findInvertedBinaryTree(root.right); temporaryHold = root.left; root.left = root.right; root.right = temporaryHold; return root }; console.log(printTree(originalTree));

This is how the problem statement shows us modular programming of algorithms from creating a node to printing nodes in BST and then finding that inverted binary tree .

### Example

The combined main code from the above algorithm looks like :

class Node { constructor(value){ this.value = value; this.left = null; this.right = null; } } const printTree = (root) => { let listOfTreeElements = []; let queueOfTreeElements = [root]; while (queueOfTreeElements.length) { let currentNode = queueOfTreeElements.shift(); listOfTreeElements.push(currentNode.value); if(currentNode.left) queueOfTreeElements.push(currentNode.left); if(currentNode.right) queueOfTreeElements.push(currentNode.right); } return listOfTreeElements; } function findInvertedBinaryTree (root) { if (root === null) return; let temporaryHold; findInvertedBinaryTree(root.left); findInvertedBinaryTree(root.right); temporaryHold = root.left; root.left = root.right; root.right = temporaryHold; return root }; let originalTree = new Node(4); originalTree.left = new Node(2); originalTree.right = new Node(7); originalTree.left.left = new Node(1); originalTree.left.right = new Node(3); originalTree.right.left = new Node(9); originalTree.right.right = new Node(0); console.log(printTree(originalTree)); console.log(' Inverted Binary Tree :'); console.log(printTree(findInvertedBinaryTree(originalTree)));

### Output

The output looks like ,

[ 4, 2, 7, 1, 3, 9, 0 ] Inverted Binary Tree : [ 4, 7, 2, 0, 9, 3, 1 ]

## Time and Space Complexity

With the recursive approach , every element or node is traversed only once for the tree inversion such that the time complexity is reduced to O(n) whereas the space complexity is proportional to the height of the binary tree or to the number of recursive calling of the function equal to the height of the tree ie. O(h) where h is the height of the tree.

## Conclusion

That is how we can solve the above problem statement by thinking modularly and logically around different sub algorithms in finding the mirror image of Binary Search Tree.

To Continue Learning Please Login

Login with Google