gpt4 book ai didi

binary-tree - 不使用递归的二叉树后序遍历

转载 作者:行者123 更新时间:2023-11-28 03:09:12 25 4
gpt4 key购买 nike

使用递归对二叉树进行后序遍历的算法是什么?

最佳答案

这是只有一个堆栈且没有已访问标志的版本:

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

boolean finishedSubtrees = (next.right == head || next.left == head);
boolean isLeaf = (next.left == null && next.right == null);
if (finishedSubtrees || isLeaf) {
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);
}
}
}
}

关于binary-tree - 不使用递归的二叉树后序遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60310138/

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