gpt4 book ai didi

java - 使用一个堆栈在二叉树中进行后序遍历

转载 作者:行者123 更新时间:2023-11-30 04:05:44 24 4
gpt4 key购买 nike

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

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

最佳答案

这是我对另一个问题( 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);
}
}
}
}

关于java - 使用一个堆栈在二叉树中进行后序遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20761133/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com