Python:迭代实现二叉树前中后序遍历【算法村E7递归笔记(黄金)】

前言

前文(白银篇)介绍了如何用递归解决二叉树的前中后序遍历问题。本文将尝试通过迭代来解决上述三个问题。


迭代解决二叉树前序遍历

题解代码如下:

class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        res = []
        node = root
        stack = []
        while stack or node:
            while node:
                res.append(node.val)
                stack.append(node)
                node = node.left
            node = stack.pop()
            node = node.right
        return res

迭代解决二叉树中序遍历

题解代码如下:

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if root is None: return []
        res = []
        stack = []
        node = root
        while stack or node:
            while node:
                stack.append(node)
                node = node.left
            node = stack.pop()
            res.append(node.val)
            node = node.right
        return res

迭代解决二叉树后序遍历

(后序是这三者中难度最高的,方法可能也最为丰富)

class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        # 方法一:递归
        res = []
        def post_order_recur(node,res):
            if node is None: return []
            post_order_recur(node.left, res)
            post_order_recur(node.right, res)
            res.append(node.val)
        post_order_recur(root, res)
        return res


        # 方法二:反转法
        # 以图示为例,后序遍历结果为[3,2,1]
        # 反转过来为[1,2,3]
        # 而这个[1,2,3]实际上是和前序遍历相同的操作
        #只不过是先右子树后左子树
        #因此思路是,我们仿写一个反过来的前序遍历,随后将结果列表翻转即可
        if root is None: return []
        res = []
        stack = []
        node = root
        while stack or node:
            while node:
                res.append(node.val)
                stack.append(node)
                node = node.right
            node = stack.pop()
            node = node.left
        return res[::-1]


        # 方法三:Morris法
        # 方法四:访问标记法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值