Question: Hi ! I need help implimenting a balance ( ) method that balances a existing BST . There is more information in the photo attached

Hi! I need help implimenting a balance() method that balances a existing BST. There is more information in the photo attached and here is the code i have so far:
public void balance()
{
LinkedList nodes = new LinkedList>();
sortNodes(nodes, root);
root = balanceTree(nodes,0, size()-1);
}
private void sortNodes(LinkedList nodes, Node n)
{
if(n == null)
{
return;
}
sortNodes(nodes, n.left);
nodes.add(n);
sortNodes(nodes, n.right);
}
private Node balanceTree(LinkedList nodes, int start, int end)
{
if(start > end)
{
return null;
}
int middle =(start + end)/2;
if((start + end)%2==1)
{
middle++;
}
Node middleNode = nodes.get(middle);
middleNode.left = balanceTree(nodes, start,middle-1);
middleNode.right = balanceTree(nodes, middle +1, end);
return middleNode;
}
It is not working correctly on some of the tests:
8.3) balance()3[Hint: Balances short left stilted tree and updates node sizes.](0/2.5) Test Failed!
Node (key:4) does not have correct N value, expected 4 found 3.
at edu.ser222.m03_02.tests.BSTTest.assertNodeNValues:425(BSTTest.java)
at edu.ser222.m03_02.tests.BSTTest.testBalance3:414(BSTTest.java)
8.4) balance()4[Hint: Balances short right stilted tree and updates node sizes.](0/2.5) Test Failed!
Node (key:5) does not have correct N value, expected 5 found 3.
at edu.ser222.m03_02.tests.BSTTest.assertNodeNValues:425(BSTTest.java)
at edu.ser222.m03_02.tests.BSTTest.testBalance4:447(BSTTest.java)
8.5) balance()5[Hint: Balances right stilted tree and updates node sizes.](0/3) Test Failed!
Node (key:6) does not have correct N value, expected 6 found 3.
at edu.ser222.m03_02.tests.BSTTest.assertNodeNValues:425(BSTTest.java)
at edu.ser222.m03_02.tests.BSTTest.testBalance5:471(BSTTest.java)
Hi ! I need help implimenting a balance ( )

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!