leetcode102 Binary Tree Level Order Traversal

Posted yawenw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 """

 

以上是关于leetcode102 Binary Tree Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 102. Binary Tree Level Order Traversal

[LeetCode]题解(python):102- Binary Tree Level Order Traversal

LeetCode 102. Binary Tree Level Order Traversal

Leetcode 102. Binary Tree Level Order Traversal

[leetcode-102-Binary Tree Level Order Traversal]

Java [Leetcode 102]Binary Tree Level Order Traversal