0
votes

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 );

  }
2
Where is your stacktrace? - reto
You're printing node.left.data and node.right.data when you call inorderHelper(node.left) and inorderHelper(node.right). - Kevin

2 Answers

4
votes

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 );

  }
0
votes

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