剑指offer刷题笔记60(python)
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路1
来自牛客大佬的思路:
利用递归,根据遍历的深度不断对结果列表进行扩充,同时根据当前深度来决定节点应该存储在列表的那个位置。
代码1
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
思路2
借助一个队列实现层次遍历。
代码2
# -*- 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 == None:
return []
list = [pRoot]
ret = []
while list:
templist = []
tempret = []
for node in list:
tempret.append(node.val)
if node.left:
templist.append(node.left)
if node.right:
templist.append(node.right)
list = templist
ret.append(tempret)
return ret