# Inserting a node in a Javascript AVL Tree

Web DevelopmentFront End TechnologyJavascript

We can learn how we can insert a node in an AVL Tree. Insertions in AVL trees are the same as BST, we just need to perform one extra step called balance tree during insert whenever we move down the tree.

This requires calculating the balance factor which we already saw before. And according to the configurations, we need to call appropriate rotation methods. These are pretty intuitive with the help of the above explanation.

We again create a class method and a helper function for recursive calls −

## Example

insert(data) {
let node = new this.Node(data);
// Check if the tree is empty
if (this.root === null) {
// Insert as the first element
this.root = node;
} else {
insertHelper(this, this.root, node);
}
}

#### Helper method

function insertHelper(self, root, node) {
if (root === null) {
root = node;
} else if (node.data < root.data) {
// Go left!
root.left = insertHelper(self, root.left, node);
// Check for balance factor and perform appropriate rotation
if (root.left !== null && self.getBalanceFactor(root) > 1) {
if (node.data > root.left.data) {
root = rotationLL(root);
} else {
root = rotationLR(root);
}
}
} else if (node.data > root.data) {
// Go Right! root.
right = insertHelper(self, root.right, node);
// Check for balance factor and perform appropriate rotation
if (root.right !== null && self.getBalanceFactor(root) < -1) {
if (node.data > root.right.data) {
root = rotationRR(root);
} else {
root = rotationRL(root);
}
}
}
return root;
}

You can test this using −

## Example

let AVL = new AVLTree();

AVL.insert(10);
AVL.insert(15);
AVL.insert(5);
AVL.insert(50);
AVL.insert(3);
AVL.insert(7);
AVL.insert(12);

AVL.inOrder();

## Output

This will give the output −

3
5
7
10
12
15
50