剑指offer 把二叉树打印成多行

把二叉树打印成多行

题目

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

方法

方法1:宽度优先遍历

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 not pRoot:
return []
import collections
queue=collections.deque([(pRoot)])
ans=[]
while queue:
level=[]
for i in range(len(queue)):
node=queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
level.append(node.val)
ans.append(level)
return ans
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 not pRoot:
return []

queue=[pRoot]
ans=[]
while queue:
value=[]
for i in range(len(queue)):
node=queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
value.append(node.val)
ans.append(value)
return ans