+ 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
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
+ 1
KrOW thank you. Iām not really experienced though so i donāt know how to use init
+ 1
by init i mean allocate them like:
left= new BinaryTree ();
right= new BinaryTree ();
like your commented code in Node constructor
+ 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
0
Triz You have to check root if is null return the left / right then call setData
0
KrOW
If u have the time, could you please do write the code so i can understand?