【发布时间】:2015-05-10 07:52:01
【问题描述】:
在使用递归时,我的二叉树的级别顺序遍历存在问题。我正在输入以下值:50,60,70,30,20,10 这是我正在使用的代码:
public void levelOrder(Node localRoot){
if(localRoot != null){
if(localRoot.leftChild != null && localRoot.rightChild != null){
System.out.print(localRoot.iData + " ");
System.out.print(localRoot.leftChild.iData + " ");
System.out.print(localRoot.rightChild.iData + " ");
levelOrder(localRoot.leftChild);
levelOrder(localRoot.rightChild);
}
else if(localRoot.rightChild == null && localRoot.leftChild == null){
;
}
else if(localRoot.rightChild == null){
System.out.print(localRoot.leftChild.iData + " ");
//levelOrder(localRoot.leftChild);
}
else{
System.out.print(localRoot.rightChild.iData + " ");
//levelOrder(localRoot.rightChild);
}
}
}
不使用堆栈是否可以递归?因为目前这个功能把我一直带到左边然后它向右走。我可以做些什么不同的事情?
我对这段代码的输出是:50、30、60、20、70,它不打印 10。
【问题讨论】:
-
与递归的处理是您不必自己管理堆栈;)。
-
我的意思是.. 任何递归方法都可以用堆栈替换,我知道我不必自己管理堆栈,但在触摸右侧之前我会一直沿着完整的左侧向下移动。
-
栈是指队列吗?如果我没记错的话,级别顺序与广度优先相同,它需要一个队列并且不是递归的。
-
看起来你在做预购遍历。 @thermite 我同意,请参阅 this link 以了解有关队列执行级别顺序的讨论。
-
因为左边的东西应该在节点之前,而右边的东西应该在进程正确运行之后出现。我建议您研究一下构建树的机制。
标签: java recursion binary-tree