码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 102. Binary Tree Level Order Traversal

时间:2019-10-21 10:03:23      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:value   cti   values   tree node   des   none   val   for   efi   

Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   /   9  20
    /     15   7

 

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]
 1 # Definition for a binary tree node.
 2 # class TreeNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution:
 9     def levelOrder(self, root: TreeNode) -> List[List[int]]:
10         res = []
11         if root is None:
12             return res
13         from collections import deque
14         queue = deque()
15         queue.append(root)
16         while queue:
17             size = len(queue)
18             lst = []
19             for i in range(size):
20                 cur = queue.popleft()
21                 lst.append(cur.val)
22                 if cur.left:
23                     queue.append(cur.left)
24                 if cur.right:
25                     queue.append(cur.right)
26             res.append(lst)
27         return res
28             
29         

 

[LC] 102. Binary Tree Level Order Traversal

标签:value   cti   values   tree node   des   none   val   for   efi   

原文地址:https://www.cnblogs.com/xuanlu/p/11711300.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!