[leetcode tree]102. Binary Tree Level Order Traversal

时间:2021-03-24 09:35:51

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]
]

按层打印树

 class Solution(object):
def levelOrder(self, root):
res,level = [],[root]
while root and level:
res.append([node.val for node in level])
level_pair = [(node.left,node.right) for node in level]
level = [leaf for lr in level_pair for leaf in lr if leaf]
return res