[leetcode tree]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]
]

按层打印树

1 class Solution(object):
2     def levelOrder(self, root):
3         res,level = [],[root]
4         while root and level:
5             res.append([node.val for node in level])
6             level_pair = [(node.left,node.right) for node in level]
7             level = [leaf for lr in level_pair for leaf in lr if leaf]
8         return res

 

posted @ 2017-03-08 20:25  wilderness  阅读(124)  评论(0编辑  收藏  举报