zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):102- Binary Tree Level Order Traversal

    题目来源:

      https://leetcode.com/problems/binary-tree-level-order-traversal/


    题意分析:

      宽度优先搜索一颗二叉树,其中同一层的放到同一个list里面。比如:

      3
       / 
      9  20
        /  
       15   7
    返回
    [
      [3],
      [9,20],
      [15,7]
    ]

    题目思路:

      新定义一个函数,加多一个层数参数,如果目前答案的列表答案个数等于层数,那么当前层数的列表append新元素,否者加新的层数。


    代码(python):

      

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def levelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            ans = []
            def bfs(root,level):
                if root != None:
                    if len(ans) < level + 1:
                        ans.append([])
                    ans[level].append(root.val)
                    bfs(root.left,level+1)
                    bfs(root.right,level+1)
            bfs(root,0)
            return ans
            
    View Code
  • 相关阅读:
    1 Anytao系列文章
    arraylist使用
    安装SQL 2005 的前提条件
    div+css
    Web MVC框架的三种类型
    使用javascript做页面间传值
    应用程序框架设计
    利用UrlRewrite,asp.net动态生成htm页面
    收集
    dwr配置
  • 原文地址:https://www.cnblogs.com/chruny/p/5251414.html
Copyright © 2011-2022 走看看