I am trying to edit a function so that it balances the binary tree as it inserts the new nodes. I cannot use libraries and it must be in raw Java.
The only help given were two sets of instructions:
1)
• How do you rotate a node?
• Node "n" needs to rotate left (it moves to the left and the node on the right replaces it)
• Right's left becomes n's right
• n's right becomes right's left
• n becomes right
LinkedNode r = n.getRight(); // Get the right node
n.setRight(r.getLeft()); // n's right becomes right's left
r.setLeft(n); // right's left becomes n
n = r; // Make n point to r now
• To tell if a node needs to be rotated, you need to know the depth on each side of the node
int ld = depth(n.getLeft());
int rd = depth(n.getRight());
if(ld-rd > 1) // Left is too long - rotate right
if(rd-ld > 1) // Right is too long - rotate left
However no matter how I try to apply these instructions, I can't get the nodes rotated correctly to balance the tree. The original function is as follows:
public void add(T val) {
LinkedNode<T> t = new LinkedNode<T>(val); // Make a new node
if (root == null)
root = t; // Empty tree, so make root the new node
else {
// If the root is less than val,
// Make val the root with the current root on the left
if (root.get().compareTo(val) < 0) {
t.setLeft(root);
}
// Otherwise, make val the root with the current root on the right
else {
t.setRight(root);
}
root = t;
}
Any help is greatly appreciated