首页 > 代码库 > Leetcode 102. Binary Tree Level Order Traversal
Leetcode 102. Binary Tree Level Order Traversal
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] ]
思路: 逐个level操作。用queue来维护每一行,对于每一行pop出第一个node的时候,把他的left和right kid push到queue里面。注意应该先算出这一行到底有多少个node (也就是当前queue的长度),否则不知道什么时候该停下来。
1 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution(object): 9 def levelOrder(self, root): 10 """ 11 :type root: TreeNode 12 :rtype: List[List[int]] 13 """ 14 if not root: 15 return [] 16 17 ans = [] 18 queue = [root] 19 while queue: 20 level = [] 21 size = len(queue) 22 for i in range(size): 23 node = queue.pop(0) 24 level.append(node.val) 25 if node.left: 26 queue.append(node.left) 27 if node.right: 28 queue.append(node.right) 29 ans.append(level) 30 return ans
Leetcode 102. Binary Tree Level Order Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。