Professional Documents
Culture Documents
22SW075
22SW075
Roll no : 22SW075
Section# : 03
TreeNode(int val) {
this.val= val;
this.height= 1;
}
}
return false;
}
static TreeNoderotateRight(TreeNodey) {
TreeNodex = y.left;
TreeNodeT2 = x.right;
x.right= y;
y.left= T2;
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;
}
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");
}
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");
}
}
}