【问题标题】:post order traversal in binary tree using one stack使用一个堆栈在二叉树中进行后序遍历
【发布时间】:2013-12-24 12:40:19
【问题描述】:

我想只使用一个堆栈对二叉树进行后序遍历。这是我的代码,首先我将左元素推入堆栈,直到达到空值。然后我弹出一个元素,检查弹出的元素和当前栈顶的右边元素是否相同。但不知何故,这将进入无限循环。你能告诉我为什么吗??

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

【问题讨论】:

  • 你能提供一个卡住的例子吗?

标签: java data-structures binary-tree tree-traversal


【解决方案1】:

这是我对另一个问题 (Post order traversal of binary tree without recursion) 的回答中的代码。它适用于一个堆栈并且不使用访问标志。

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

【讨论】:

    【解决方案2】:

    为什么不递归呢?

    public void postorder(BinNode root) {
        if (root == null)
            return;
        postorder(root.getLeft());
        postorder(root.getRight());
        System.out.println(root.getKey());
    }
    

    【讨论】:

    • 当然这是一种方法,但正在寻找其他选择。
    【解决方案3】:

    这段代码中有一个无限循环,让我们考虑一棵右斜树来说明这一点:

    1 有一个右孩子 2

    2 有一个右孩子 3

    3 是叶节点

    在前 3 个循环中,1、2、3 将被压入堆栈。 现在在第四个循环中,它进入 else 部分,现在它打印 3 后跟 2 并弹出两者。

    声明之后

    else if( s.top().getRight()==null) 
    

    声明

    if(!s.isEmpty()) 
    

    将 2 再次压入堆栈。这会导致无限循环。

    代码有缺陷。

    声明

    if(root==s.top().getRight()) 
    

    应该变成一个while循环来解决这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 2014-05-08
      • 2012-09-23
      • 2012-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多