题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
python solution:
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def Print(self, pRoot):
if not pRoot:
return []
stack = [pRoot]
res = []
while len(stack):
l = len(stack)
tempres = []
for i in range(l):
temp = stack.pop(0)
tempres.append(temp.val)
if temp.left:
stack.append(temp.left)
if temp.right:
stack.append(temp.right)
res.append(tempres)
return res