+ 1

Can someone help me please (Inserting into binary tree error) ?

So I created a main method in the class Tester1 and I am trying to insert characters to create a binary tree using a sequence of insertNode, getLeft, and getRight operations but I'm getting this error: Exception in thread "main" java.lang.NullPointerException: Cannot invoke "BinaryTree.emptyTree()" because the return value of "Node.getRightChild()" is null at BinaryTree.insertNode(BinaryTree.java:142) at Tester1.main(Tester1.java:14) https://code.sololearn.com/cHbqVw5r2DHU/?ref=app

31st Oct 2022, 1:41 AM
Triz
Triz - avatar
6 Answers
+ 2
The exception description tell you alll... getRightChild return null and, because you call on return value the method emptyTree, a NullPointerException is raised (you cannot call a method on null, right?). Left and right are null at contruction time than you will have this exception when try to access as a valid not-null object (like above)... An easy solution is init right and left in Node ctor but i dont read all code and i dont know if other problems can raise
31st Oct 2022, 7:03 AM
KrOW
KrOW - avatar
+ 1
KrOW thank you. I’m not really experienced though so i don’t know how to use init
31st Oct 2022, 8:54 PM
Triz
Triz - avatar
+ 1
by init i mean allocate them like: left= new BinaryTree (); right= new BinaryTree (); like your commented code in Node constructor
1st Nov 2022, 9:18 AM
KrOW
KrOW - avatar
+ 1
KrOW thank you! It runs without error now. Have you any idea how i can use getleft() and getright() to insert characters in the tree? The method is in the class, Tester1
1st Nov 2022, 1:22 PM
Triz
Triz - avatar
0
Triz You have to check root if is null return the left / right then call setData
2nd Nov 2022, 6:02 AM
KrOW
KrOW - avatar
0
KrOW If u have the time, could you please do write the code so i can understand?
2nd Nov 2022, 7:27 AM
Triz
Triz - avatar