简体   繁体   English

按顺序打印二进制搜索树

[英]Printing Binary Search Tree in-order Traversal

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,4,11和12,我希望我的输出看起来像:

1: Right Subtree: 12 1:右子树:12

4: Right Subtree: 11 4:右子树:11

11: Leaf node 11:叶节点

12: Left Subtree: 4 etc 12:左子树:4等

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

  }

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. 这是一个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 );

  }

您只应打印node.data ,递归将按顺序打印左右树。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM