zoukankan      html  css  js  c++  java
  • leetcode102 Binary Tree Level Order Traversal

     1 """
     2 Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
     3 For example:
     4 Given binary tree [3,9,20,null,null,15,7],
     5     3
     6    / 
     7   9  20
     8     /  
     9    15   7
    10 return its level order traversal as:
    11 [
    12   [3],
    13   [9,20],
    14   [15,7]
    15 ]
    16 
    17 """
    18 class TreeNode:
    19     def __init__(self, x):
    20         self.val = x
    21         self.left = None
    22         self.right = None
    23 
    24 class Solution:
    25     def levelOrder(self, root):
    26         if root ==  None:    #树为空,直接返回[]
    27             return []
    28         queue = [root]
    29         cur = []
    30         res = []
    31         while queue:
    32             cur = [x.val if x else None for x in queue] #存当前层的value
    33             newqueue = []                   #newqueue用来遍历下一层使用
    34             for x in queue:
    35                 if x.left:                  #bug 如果不判断,结果包含[None]
    36                     newqueue.append(x.left)
    37                 if x.right:
    38                     newqueue.append(x.right)
    39             queue = newqueue
    40             res.append(cur)                 #将当前[]append到最后结果
    41         return res
    42 """
    43 本题与leetcode101相似,用BFS可解
    44 """
  • 相关阅读:
    数据结构——第二章 线性结构
    数据结构——第一章 绪论
    2018年
    Node笔记(2)
    Node笔记(1)
    公务员考试
    cf-789A (思维)
    cf188C(最大子段和&&思维)
    zzuli1731 矩阵(容斥)
    九余数定理(同余定理)
  • 原文地址:https://www.cnblogs.com/yawenw/p/12254013.html
Copyright © 2011-2022 走看看