Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

How can I get this binary tree system in Java to work? I am trying to use Consum

ID: 3882690 • Letter: H

Question

How can I get this binary tree system in Java to work?

I am trying to use Consumer<E> to create a binary tree, and when I run tests, I keep getting NullPointerExceptions. My tree is made of binary nodes. I want to use consumer to get this right, and so here I have

My nodes:

I know, I think I have the algorithm down for preorder, inorder, and postorder. Yet after the tree, my test fails.

My tree:

public class BinaryTree<E> {
private BinaryNode<E> root;

public BinaryTree(){
root = null;
}
public BinaryTree(BinaryNode<E> r){
root = r;
}

public void preorder(Consumer<E> c){
root.preorder(c);
}
public void inorder(Consumer<E> c){
root.inorder(c);
}
public void postorder(Consumer<E> c){
root.postorder(c);
}

}

but when I run this, I get NPEs:

BinaryNode<Integer> n0 = new BinaryNode<>(2,null,null);
BinaryNode<Integer> n1 = new BinaryNode<>(5,null,null);
BinaryNode<Integer> n2 = new BinaryNode<>(5,n0,n1);
BinaryNode<Integer> n3 = new BinaryNode<>(8, null, null);
BinaryNode<Integer> n4 = new BinaryNode<>(7, null, n3);
BinaryNode<Integer> root = new BinaryNode<>(6, n2, n4);
T = new BinaryTree<>(root);
ArrayList<Integer> lst = new ArrayList<>();
T.preorder((Integer q) -> { lst.add(q); });
int anticipated[] = { 6, 5, 2, 5, 7, 8 };
for (int i = 0; i != anticipated.length; ++i)
assertEquals((Integer)anticipated[i], lst.get(i));
}   

My test fails. It gives me IndexOutOfBounds. The other methods, inorder and postorder don't work either.

Explanation / Answer

Your tree code part looks fine but the problem is with for loop at the end , change the for loop as below and try to remove IndexOutOfBounds:(Comment for queries)

for (int i = 0; i < anticipated.length; i++)
assertEquals((Integer)anticipated[i], lst.get(i));

In the code that you provide , you should increment i , i++

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote