0

I've created a program that stores integers from user input in a binary search tree and I have recursive functions for pre, post and in-order traversals that work fine. What I'm trying to do is traverse the tree in-order and at each node I want to print the number that is stored there and the number in the node to the left and right of it or if the node is a leaf node. Assuming the user enters the integers 1,4,11 and 12 I want my output to look like:

1: Right Subtree: 12

4: Right Subtree: 11

11: Leaf node

12: Left Subtree: 4 etc

here is the code I am using for the function, when I run the program I am getting a null pointer exception.

 public synchronized void inorderTraversal()
  { inorderHelper( root ); }

// Recursive method to perform inorder traversal

private void inorderHelper( TreeNode node )
  {
      if ( node == null )
        return;

     inorderHelper( node.left );
     System.out.print( node.data + ":  Left Subtree " + node.left.data +": Right Subtree " + node.right.data);
     inorderHelper( node.right );

  }
user3415930
  • 1
  • 1
  • 1
  • 2

2 Answers2

4

Chances are, your recursion is taking you to the bottom level of your tree (your leaves) and when you attempt to call

node.left.data

it's a null => NullPointerException.

As others are saying, just let your recursion take care of the work.

private void inorderHelper( TreeNode node )
  {
      if ( node == null )
        return;

     inorderHelper( node.left );
     System.out.print( "Node data: " + node.data);
     inorderHelper( node.right );

  }
Reuben Tanner
  • 5,229
  • 3
  • 31
  • 46
  • @user3415930, did this answer help you? Typically, if it did, you upvote it and give it a checkmark so the person who answered gets some points. – Reuben Tanner Mar 27 '14 at 23:09
0

You should only print node.data, the recursion will take care of printing the left and right trees in-order.

Anthony Accioly
  • 21,918
  • 9
  • 70
  • 118