题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路:
1、把每层节点的val值用list存好
2、把每层节点存好:
①计算当层节点的个数,这样就保证下一步每层的结点都被pop光
②然后依次弹出从左到右的每个节点,然后在list中加入该节点对应的左结点、右节点(如果存在的话)
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表[[1,2],[4,5]]
def Print(self, pRoot):
if not pRoot :
return []
queue = [pRoot]
result = []
while (queue):
size = len(queue)
row = []
for i in queue:
row.append(i.val)
result.append(row)
for i in range(size):
node = queue.pop(0)
if (node.left is not None):
queue.append(node.left)
if (node.right is not None):
queue.append(node.right)
return result