Skip to content

Commit 04f4c8f

Browse files
committed
balance factor fixed
1 parent 838c350 commit 04f4c8f

File tree

3 files changed

+29
-17
lines changed

3 files changed

+29
-17
lines changed

build/classes/Trees/AVL.class

834 Bytes
Binary file not shown.

build/classes/Trees/Main.class

34 Bytes
Binary file not shown.

src/Trees/AVL.java

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ private int getBalanceFactor(AVLNode node) {
3030
if (node == null) {
3131
return 0;
3232
}
33-
return getHeight(node.left) - getHeight(node.left);
33+
return getHeight(node.left) - getHeight(node.right);
3434
}
3535

3636
private AVLNode add(int val, AVLNode root) {
@@ -45,23 +45,21 @@ private AVLNode add(int val, AVLNode root) {
4545
}
4646
root.height = 1 + Math.max(getHeight(root.left), getHeight(root.right));
4747
int balanceFactor = getBalanceFactor(root);
48-
// Left Left Rotation
49-
if (balanceFactor > 1 && root.left.val > val) {
50-
root = leftRotate(root);
48+
if (balanceFactor > 1) {
49+
if (val < root.left.val) {
50+
return rightRotate(root);
51+
} else if (val > root.left.val) {
52+
root.left = leftRotate(root.left);
53+
return rightRotate(root);
54+
}
5155
}
52-
// Right Right Rotation
53-
if (balanceFactor < -1 && root.right.val < val) {
54-
root = rightRotate(root);
55-
}
56-
// Left Right Rotation
57-
if (balanceFactor > 1 && root.left.val < val) {
58-
root.left = leftRotate(root.left);
59-
root = rightRotate(root);
60-
}
61-
// Right Left Rotation
62-
if (balanceFactor < -1 && root.right.val > val) {
63-
root.right = rightRotate(root.right);
64-
root = leftRotate(root);
56+
if (balanceFactor < -1) {
57+
if (val > root.right.val) {
58+
return leftRotate(root);
59+
} else if (val < root.right.val) {
60+
root.right = rightRotate(root.right);
61+
return leftRotate(root);
62+
}
6563
}
6664
return root;
6765
}
@@ -106,4 +104,18 @@ public String toString() {
106104
return inOrder().toString();
107105
}
108106

107+
public void display() {
108+
display(root);
109+
}
110+
111+
private void display(AVLNode node) {
112+
if (node == null) {
113+
System.out.print(null + " ");
114+
return;
115+
}
116+
System.out.print(node.val + " ");
117+
display(node.left);
118+
display(node.right);
119+
}
120+
109121
}

0 commit comments

Comments
 (0)