Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Name :MOIN HAIDER

Roll no : 22SW075

Section# : 03

Assignment topic : AVL Tree


class TreeNode{
int val;
TreeNodeleft, right;
int height;

TreeNode(int val) {
this.val= val;
this.height= 1;
}
}

public class AVL_Tree{


public static boolean isAVL(TreeNoderoot) {
if (root == null)
return true;

int leftHeight= height(root.left);


int rightHeight= height(root.right);

if (Math.abs(leftHeight- rightHeight) <= 1 &&isAVL(root.left) &&isAVL(root.right))


return true;

return false;
}

public static int height(TreeNodenode) {


if (node == null)
return 0;

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


}

static TreeNoderotateRight(TreeNodey) {
TreeNodex = y.left;
TreeNodeT2 = x.right;
x.right= y;
y.left= T2;

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


x.height= Math.max(height(x.left), height(x.right)) + 1;
return x;
}
static TreeNoderotateLeft(TreeNodex) {
TreeNodey = x.right;
TreeNodeT2 = y.left;

y.left= x;
x.right= T2;
x.height= Math.max(height(x.left), height(x.right)) + 1;
y.height= Math.max(height(y.left), height(y.right)) + 1;
return y;
}
public static TreeNodebalance(TreeNoderoot) {
if (root == null)
return null;
int balanceFactor= height(root.left) - height(root.right);

// Left heavy
if (balanceFactor>1) {
if (height(root.left.left) >= height(root.left.right))
return rotateRight(root);

else {
root.left= rotateLeft(root.left);
return rotateRight(root);
}
}
// Right heavy
else if (balanceFactor< -1) {
// Right-Right case
if (height(root.right.right) >= height(root.right.left))
return rotateLeft(root);
// Right-Left case
else {
root.right= rotateRight(root.right);
return rotateLeft(root);
}
}

return root;
}

public static void main(String[] args) {


// Example 1
TreeNoderoot1 = new TreeNode(1);
root1.left = new TreeNode(2);
root1.right = new TreeNode(3);

if (isAVL(root1))
System.out.println("Tree 1 is AVL tree");
else {
System.out.println("Tree 1 is not AVL tree");
root1 = balance(root1);
System.out.println("After balancing:");
if (isAVL(root1))
System.out.println("Tree 1 is now AVL tree");
else
System.out.println("Tree 1 is still not AVL tree");
}

TreeNoderoot2 = new TreeNode(1);


root2.left = new TreeNode(2);
root2.left.left = new TreeNode(3);

if (isAVL(root2))
System.out.println("Tree 2 is AVL tree");

else {
System.out.println("Tree 2 is not AVL tree");
root2 = balance(root2);
System.out.println("After balancing:");
if (isAVL(root2))
System.out.println("Tree 2 is now AVL tree");
else
System.out.println("Tree 2 is still not AVL tree");
}
}
}

You might also like