其他分享
首页 > 其他分享> > Iterative Postorder Traversals of Binary Tree

Iterative Postorder Traversals of Binary Tree

作者:互联网

二叉树非递归后序遍历

1. Using 1 stack

O(n) time, O(n) space
初始设置栈为空,当前节点为根节点

执行以下操作,直到栈为空当前节点为空时停止:

stack = []
node = root
while node and stack:
    if node:
        stack.append(node)
        node = node.left
    else:
        node = stack[-1]
        if not node.right or node.right == prev:
            print(node.val)
            stack.pop()
            node = None
        else:
            node = node.right

2. Using 2 stacks

O(n) time, O(n) space
stack: 用于储存和遍历子节点,初始化=[root]
path: 记录从根节点到当前节点的路径

执行以下操作,直到stack为空:

stack = [root]
path = []
while stack:
    node = stack.pop()
    if path and path[-1] == node:
        path.pop()
        print(node.val)
    else:
        path.append(node)
        if node.right: stack.append(node.right)
        stack.append(node)
        if node.left: stack.append(node.left)

3. Using no stacks (Morris traversal)

O(n) time, O(1) space
在中序morris traversal的基础上作修改,遍历顺序由 “左根右” 变为 “左右根”。一种方法是添加dummy节点使得根节点为其左孩子,然后使用reverse辅助函数将每一层 “根到最右” 的部分反转,遍历该层之后再反转恢复结构。图片来源是leetcode用户xruzty这篇文章
在这里插入图片描述
新建dummy节点,设置其左孩子为root
初始化node = dummy
进行以下操作直到node为空:

def reverse(start, end):
    if start == end:
        return
    prev = start
    node = start.right
    while prev != to:
        tmp = node.right
        node.right = prev
        prev = node
        node = tmp


dummy = TreeNode(None)
dummy.left = root
node = dummy
while node and node.val:
    if node.left:
        prev = node.left
        while prev.right and prev.right != node:
            prev = prev.right
        if not prev.right:
            prev.right = node
            node = node.left
        else:
            reverse(node.left, prev)
            tmp = prev
            while tmp != node.left:
                print(tmp.val)
                tmp = tmp.right
            print(tmp.val)  # print node.left.val
            prev.right = None
            node = node.right
    else:
        node = node.right

参考资料:
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/45648/three-ways-of-iterative-postorder-traversing-easy-explanation

标签:node,Binary,right,Traversals,Iterative,stack,prev,节点,left
来源: https://blog.csdn.net/wjykst/article/details/120464916