zoukankan      html  css  js  c++  java
  • 102. 二叉树的层序遍历



    方法一:广搜,迭代

    class Solution(object):
        # 相当于广度优先搜索,使用队列实现。
        # 队列初始化,将根节点压入队列。
        # 当队列不为空,进行如下操作:
        # 弹出一个节点,访问,若左子节点或右子节点不为空,将其压入队列。
        def levelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            if not root:
                return []
            level_queue = []
            ans = []
            level_queue.append(root)
            while level_queue:
                num = len(level_queue)
                temp = []
                while num > 0:
                    cur = level_queue.pop(0)
                    temp.append(cur.val)
                    if cur.left:
                        level_queue.append(cur.left)
                    if cur.right:
                        level_queue.append(cur.right)
                    num -= 1
                ans.append(temp)
            return ans
    

    方法二:深搜,递归

    class Solution(object):
        def levelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            if not root:
                return []
            ans = []
            self.dfs(1, root, ans)
            return ans
    
        def dfs(self, level, root, ans):
            if len(ans) < level:
                ans.append([])
            ans[level - 1].append(root.val)
            if root.left:
                self.dfs(level + 1, root.left, ans)
            if root.right:
                self.dfs(level + 1, root.right, ans)
            return ans
    
  • 相关阅读:
    PAT 1012 数字分类
    PAT 1046 划拳
    PAT 1021 个位数统计
    PAT 1003 我要通过!
    PAT 1031 查验身份证
    安装swoole
    PHP yield 分析,以及协程的实现,超详细版(上)
    PHP性能优化利器:生成器 yield理解
    swoole深入学习 8. 协程 转
    swoole| swoole 协程初体验 转
  • 原文地址:https://www.cnblogs.com/panweiwei/p/13585583.html
Copyright © 2011-2022 走看看