[剑指Offer]把二叉树打印成多行

题目描述

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

解题思路

二叉树层次遍历略作修改即可。

代码

Python(2.7.3)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# -*- 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):
# write code here
if pRoot is None:
return []
queue = [pRoot]
res = []
while queue:
tmp_queue = []
tmp_queue_val = []
for tmp in queue:
tmp_queue_val.append(tmp.val)
if tmp.left is not None:
tmp_queue.append(tmp.left)
if tmp.right is not None:
tmp_queue.append(tmp.right)
queue = tmp_queue
res.append(tmp_queue_val)
return res

运行时间:33ms
占用内存:5868k