题目描述:
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路:
当前层的节点存在l1中,每次遍历l1,将l1中的子节点加入到l2中,将l1中的值加入到cur_list中
代码:
class Solution:
# 返回二维列表[[1,2],[4,5]]
def Print(self, pRoot):
# write code here
if not pRoot:
return []
l1 = [pRoot]
l2 = []
res = []
while l1:
cur_list = []
for node in l1:
cur_list.append(node.val)
if node.left:
l2.append(node.left)
if node.right:
l2.append(node.right)
l1 = l2
l2 = []
res.append(cur_list)
return res