二叉树前中后层序遍历的总结对比

二叉树结构的定义:

 # Definition for a binary tree node.
 class TreeNode:
     def __init__(self, val=0, left=None, right=None):
         self.val = val
         self.left = left
         self.right = right

在这里插入图片描述
对于以上二叉树,其四种遍历顺序分别是:
中序(左中右):7-2-1-8-4-3-5
前序(中左右):1-2-7-8-3-4-5
后序(左右中):7-8-2-4-5-3-1
层序(逐层自左向右):1-2-3-7-8-4-5

递归法

对于前中后序遍历,使用递归法最容易实现,只需要调用函数的顺序即可。

前序

class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        def travelsal(root):
            if root == None:
                return 
            res.append(root.val)  # 中
            travelsal(root.left)   # 左
            travelsal(root.right)  # 右
        travelsal(root)
        return res

中序

class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        def travelsal(root):
            if root == None:
                return 
            travelsal(root.left)   # 左
            res.append(root.val)  # 中
            travelsal(root.right)  # 右
        travelsal(root)
        return res

后序

class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        def travelsal(root):
            if root == None:
                return 
            travelsal(root.left)   # 左
            travelsal(root.right)  # 右
            res.append(root.val)   # 中
        travelsal(root)
        return res

迭代法

层序遍历(基于队列实现)

通过队列的先进先出来实现按层输出

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        res = []
        queue = [root]
        if not root:
            return res
        while queue:
            path = []
            for i in range(len(queue)):  # 对该层进行遍历
                cur = queue.pop(0)
                path.append(cur.val)
                if cur.left:
                    queue.append(cur.left)
                if cur.right:
                    queue.append(cur.right)
            res.append(path)  # 遍历完一层加到res
        return res

中序遍历(基于栈)

左中右,要注意原则 左链入栈

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        path = []
        st = []
        cur = root
        while cur:  # 先走到左链的最下面
            st.append(cur)
            cur = cur.left
        while st:
            node = st.pop()
            path.append(node.val)
            p = node.right
            while p:  # 只对左链入栈
                st.append(p)
                p = p.left
        return path

前序遍历(基于栈)

中左右,当前节点先入path,在右节点入栈,左节点入栈

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

后序遍历(基于栈)

后:左右中,其逆序为 中右左,类似于前序的中左右
所以在前序遍历的基础上,左右节点入栈顺序调换下,在逆序输出

class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        stack = [root]
        if not root:
            return res
        while stack:
            cur = stack.pop()
            if cur.left:
                stack.append(cur.left)
            if cur.right:
                stack.append(cur.right)
            res.append(cur.val)
        return res[::-1]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Weiyaner

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值