Java 二叉树的单栈后序遍历
我想只使用一个堆栈对二叉树进行后序遍历。这是我的代码,首先我将左元素推入堆栈,直到达到null。然后我弹出一个元素,检查弹出的元素和当前栈顶的右元素是否相同。但不知何故,这是进入无限循环。你能告诉我为什么吗Java 二叉树的单栈后序遍历,java,data-structures,binary-tree,tree-traversal,Java,Data Structures,Binary Tree,Tree Traversal,我想只使用一个堆栈对二叉树进行后序遍历。这是我的代码,首先我将左元素推入堆栈,直到达到null。然后我弹出一个元素,检查弹出的元素和当前栈顶的右元素是否相同。但不知何故,这是进入无限循环。你能告诉我为什么吗 public void postorderonestack(BinNode root) { BinStack s=new BinStack(); while(true) { if(root!=null) { s.
public void postorderonestack(BinNode root)
{
BinStack s=new BinStack();
while(true)
{
if(root!=null)
{
s.push(root);
root=root.getLeft();
}
else
{
if(s.isEmpty())
{
System.out.println("Stack is Empty");
return;
}
else if( s.top().getRight()==null)
{
root=s.pop();
System.out.println(root.getKey());
if(root==s.top().getRight())
{
System.out.print(s.top().getKey());
s.pop();
}
}
if(!s.isEmpty())
root=s.top().getRight();
else root=null;
}
}
}
这个代码中有一个无限循环,让我们考虑右偏斜树到ILUSTARTET: 1有权生孩子2
2有权生孩子3 3是叶节点 在前3个循环中,1、2、3将被推送到堆栈上。 现在在第四个循环中,它进入其他部分,现在它打印3,然后是2,并同时弹出 声明之后else if( s.top().getRight()==null)
声明
if(!s.isEmpty())
if(root==s.top().getRight())
将在堆栈上再次推2。这会导致无限循环
代码有缺陷
声明
if(!s.isEmpty())
if(root==s.top().getRight())
应该变成一个while循环来解决这个问题。为什么不递归地执行呢
public void postorder(BinNode root) {
if (root == null)
return;
postorder(root.getLeft());
postorder(root.getRight());
System.out.println(root.getKey());
}
这是我对另一个问题()的回答中的代码。它只使用一个堆栈,不使用访问标志
private void postorder(Node head) {
if (head == null) {
return;
}
LinkedList<Node> stack = new LinkedList<Node>();
stack.push(head);
while (!stack.isEmpty()) {
Node next = stack.peek();
if (next.right == head || next.left == head ||
(next.left == null && next.right == null)) {
stack.pop();
System.out.println(next.value);
head = next;
}
else {
if (next.right != null) {
stack.push(next.right);
}
if (next.left != null) {
stack.push(next.left);
}
}
}
}
private void postorder(节点头){
if(head==null){
返回;
}
LinkedList堆栈=新建LinkedList();
栈.推(头);
而(!stack.isEmpty()){
Node next=stack.peek();
如果(next.right==头部| | next.left==头部||
(next.left==null&&next.right==null)){
stack.pop();
System.out.println(next.value);
头=下一个;
}
否则{
if(next.right!=null){
栈.推(下一个.右);
}
if(next.left!=null){
栈.推(下一个.左);
}
}
}
}
你能提供一个它被卡住的例子吗?当然这是一种方法,但要找到其他的选择。