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
    
  • 相关阅读:
    hrbust1841再就业(状态压缩dp)
    并查集 poj2236
    JavaScript 常用单词整理
    HTML/CSS 常用单词整理
    HTML/CSS 知识点
    JavaScript 知识点
    ArcGIS裁剪影像数据
    小小程序员
    ArcGIS平面阴影制作
    前端相关的seo技术
  • 原文地址:https://www.cnblogs.com/panweiwei/p/13585583.html
Copyright © 2011-2022 走看看