题目:
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路一:
BFS
代码:
class Solution:
# 返回二维列表[[1,2],[4,5]]
def Print(self, pRoot):
queue, res = [], []
queue.append(pRoot)
while queue:
lst = []
index = 0
length = len(queue)
while index < length:
p = queue.pop(0)
if p:
queue.append(p.left)
queue.append(p.right)
lst.append(p.val)
index += 1
if lst: res.append(lst)
return res
思路二:
递归
代码:
class Solution:
# 返回二维列表[[1,2],[4,5]]
def Print(self, pRoot):
res = []
depth = 1
self.helper(pRoot, depth, res)
return res
def helper(self, p, depth, res):
if not p: return None
if depth > len(res):
res.append([])
res[depth-1].append(p.val)
self.helper(p.left, depth+1, res)
self.helper(p.right, depth+1, res)