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

  }
2
  • Where is your stacktrace? Commented Mar 27, 2014 at 21:42
  • You're printing node.left.data and node.right.data when you call inorderHelper(node.left) and inorderHelper(node.right). Commented Mar 27, 2014 at 21:43

2 Answers 2

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

  }
Sign up to request clarification or add additional context in comments.

1 Comment

@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.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.