Java 打印二叉搜索树中序遍历
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22699798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing Binary Search Tree in-order Traversal
提问by user3415930
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:
我创建了一个程序,该程序将用户输入的整数存储在二叉搜索树中,并且我有递归函数用于 pre、post 和 in-order 遍历,可以正常工作。我想要做的是按顺序遍历树,在每个节点上,我想打印存储在那里的数字以及节点中左侧和右侧的数字,或者该节点是否是叶节点。假设用户输入整数 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 );
}
回答by Anthony Accioly
You should only print node.data
, the recursion will take care of printing the left and right trees in-order.
您应该只打印node.data
,递归将负责按顺序打印左右树。
回答by Hypothetical inthe Clavicle
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 );
}