题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路及Python实现
思路一
- 思路和前面打印“之字形”一样,不过这题是每一行打印时,不需要变换数据装入的顺序,所以用队列会更好
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def Print(self, pRoot):
if pRoot is None:
return []
queue1 = [pRoot]
queue2 = []
ret = []
while queue1 or queue2:
if queue1:
temp_ret = []
while queue1:
temp_node = queue1.pop(0)
temp_ret.append(temp_node.val)
if temp_node.left:
queue2.append(temp_node.left)
if temp_node.right:
queue2.append(temp_node.right)
ret.append(temp_ret)
if queue2:
temp_ret = []
while queue2:
temp_node = queue2.pop(0)
temp_ret.append(temp_node.val)
if temp_node.left:
queue1.append(temp_node.left)
if temp_node.right:
queue1.append(temp_node.right)
ret.append(temp_ret)
return ret
思路二:递归实现
- 利用递归,根据遍历的深度不断对结果列表进行扩充,同时根据当前深度来决定节点应该存储在列表的那个位置。
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
list = []
return self.depth(pRoot, 1, list)
def depth(self, root, depth, list): # 深度递归
# depth表示当前遍历位置的深度(层次)
if root == None:
return list
if depth > len(list): # depth大于list的长度就表明,已经遍历到下一层了,需要在对list扩容
list.append([])
list[depth - 1].append(root.val) # 将当前层次的root存在对应位置的list中的数组中
self.depth(root.left, depth + 1, list) # 对当前节点的子节点进行递归
self.depth(root.right, depth + 1, list)
return list