def postorder(root): if root is None: return [] stack = [] result = [] visited = set() stack.append(root) while stack: curr = stack[-1] if (curr.left is None or curr.left in visited) and (curr.right is None or curr.right in visited): stack.pop() visited.add(curr) result.append(curr.value) else: if curr.right is not None and curr.right not in visited: stack.append(curr.right) if curr.left is not None and curr.left not in visited: stack.append(curr.left) for i in result: print(i,end=",") return result
时间: 2024-02-10 16:19:08 浏览: 63
erchashu.rar_EBADCFHGIKJ_site:www.pudn.com
这是一段二叉树后序遍历的代码,它采用了迭代的方式实现。具体实现方式是通过使用一个栈来模拟递归过程,先将根节点压入栈中,然后进行循环。每次循环时,取出栈顶元素,如果它的左右子节点都已经被访问过了,就将它弹出栈,并将它的值加入到结果列表中,否则将它的右子节点和左子节点依次压入栈中。最后输出结果列表即可。
你有什么其他问题吗?
阅读全文