题目描述:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路:
从上到下遍历二叉树,利用列表存储二叉树每一层的节点,在读取列表中当前层节点的同时,存储下一层的节点,以此类推
# -*- 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 []
#存放每层结点值
nodeStack = [pRoot]
#存放最终输出结果
result = []
while nodeStack:
res = []
nextStack = []
for i in nodeStack:
res.append(i.val)
if i.left:
nextStack.append(i.left)
if i.right:
nextStack.append(i.right)
nodeStack = nextStack
result.append(res)
return result