0

I'm getting this error when I run my code to see if a Binary Tree is full: The error I'm getting from my code is:

Exception in thread "main" java.lang.NullPointerException: **Cannot invoke 
"BinaryTree$Node.isAFullTree()" because "this.right" is null**
at BinaryTree$Node.isAFullTree(BinaryTree.java:97)
at BinaryTree$Node.isAFullTree(BinaryTree.java:97)
at BinaryTree$Node.isAFullTree(BinaryTree.java:97)
at BinaryTree.isAFullTree(BinaryTree.java:209)
at Main.main(Main.java:30)
public boolean isAFullTree () 
   if(left == null && right != null
          {
                  return false;
          }

           if(left != null && right == null
          {
                  return false;
          }

           return true  && right.isAFullTree() && left.isAFullTree(); // This line throws the exception
          }
} 
 

Gary Liu
  • 1
  • 1
  • *"...I'm getting this error when I compile my code..."* -- impossible. This can only be thrown when you *run* your code, not when you compile it. And you need to show which line throws the exception and which variable on that line is null when it is thrown. – Hovercraft Full Of Eels Nov 08 '20 at 00:54
  • So again, what are the values held by right and left when the exception is thrown? – Hovercraft Full Of Eels Nov 08 '20 at 00:57
  • A bet: ***both*** are null. Your code does not account for this. – Hovercraft Full Of Eels Nov 08 '20 at 00:58
  • Thanks a lot. Both are null and it gave me the correct output. Sorry, i'm kind of new to this. – Gary Liu Nov 08 '20 at 01:03
  • In the future, search on the error type. If you search out NullPointerException, you'd find the duplicate, which would have told you to find the offending line, and to test the variables on that line. That would have either given you the problem and the solution, or helped you to include all the needed information in your question from the start. Glad that you've got it solved. – Hovercraft Full Of Eels Nov 08 '20 at 01:12

0 Answers0