二叉树打印

按层打印二叉树

任务描述:有一课二叉树,设计一个算法,按照层次打印这棵二叉树。给定二叉树的根节点root,返回打印结果数组,结果按照每一层一个数组进行储存,数组排列顺序按照从上到下,数组内元素顺序按从左往右。

Python实现

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
27
28
29
30
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None


class TreePrinter:
def printTree(self, root):
# write code here
if root is None:
return []
else:
queue = [root, "#"]
res = []
temp = []
while queue:
cur = queue.pop(0)
if cur == "#":
res.append(temp)
temp = []
else:
temp.append(cur.val)
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
if queue[0] == "#":
queue.append("#")
return res[:-1]