python Morris 前中序遍历

不同于平常递归,或迭代遍历二叉树的,Morris遍历算法

该算法能将使用递归、DFS或BFS算法的二叉树遍历的空间复杂度由O(n)降为O(1)
关键:将当前的左节点的最右节点指向当前节点

前序遍历

tmp=None;Preorder=[]
while root:
    if root.left:
        tmp=root.left
        while tmp.right and tmp.right!=root:
            tmp=tmp.right
        if not tmp.right:
            Preorder.append(root.val) # 前序遍历
            tmp.right=root
            root=root.left
        else:
            tmp.right=None
            root=root.right
    else:
        Preorder.append(root.val) #前序遍历
        root=root.right
print(Preorder)

中序遍历

tmp=None;Inorder=[]
while root:
    if root.left:
        tmp=root.left
        while tmp.right and tmp.right!=root:
            tmp=tmp.right
        if not tmp.right:
            tmp.right=root
            root=root.left
        else:
            Inorder.append(root.val) # 中序遍历
            tmp.right=None
            root=root.right
    else:
        Inorder.append(root.val) #中序遍历
        root=root.right
print(Inorder)

猜你喜欢

转载自blog.csdn.net/weixin_46119529/article/details/129890240