0% found this document useful (0 votes)
51 views2 pages

Avl PDF

This Java class defines an AVLTree data structure. It contains a private Node root field and public insert method to add nodes by calling a private recursive insert method. This insert method balances the tree by checking the balance factor and height of nodes and restructuring if the tree becomes left or right heavy. It also contains private methods to calculate balance factor, check heaviness, and get node height.

Uploaded by

Mouad Youssef
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views2 pages

Avl PDF

This Java class defines an AVLTree data structure. It contains a private Node root field and public insert method to add nodes by calling a private recursive insert method. This insert method balances the tree by checking the balance factor and height of nodes and restructuring if the tree becomes left or right heavy. It also contains private methods to calculate balance factor, check heaviness, and get node height.

Uploaded by

Mouad Youssef
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

package com.github.YoussefMouad.DataStructures.

Trees ;

public class AVLTree {


private Node root;

public void insert(int item) {


root = insert(root, item);
}

private Node insert(Node node, int item) {


if (node == null)
return new Node(item);

if (item < node.value)


node.left = insert(node.left, item);
else node.right = insert(node.right, item);

node.height = Math.max(height(node.left),
height(node.right)) + 1;

if (isLeftHeavy(node))
System.out.println();
else if (isRightHeavy(node))
System.out.println();

return node;
}

private int balanceFactor(Node node) {


return node == null ? 0 : height(node.left) -
height(node.right);
}

private boolean isLeftHeavy(Node node) {


return balanceFactor(node) > 1;
}

private boolean isRightHeavy(Node node) {


return balanceFactor(node) < -1;
}

private int height(Node node){


return node == null ? -1 : node.height;
}

private static class Node {


private final int value;
private int height;
private Node left;
private Node right;

public Node(int value) {


this.value = value;
}

@Override
public String toString() {
return "Node = " + value;
}
}
}

You might also like