题目1:Leecode-107
给定一个二叉树,从左向右地,自底向上的遍历每一层的元素。
例:给定二叉树:
3
/ \
9 20
/ \
15 7
返回的结果:
[
[15,7],
[9,20],
[3]
]
首先,要有一个概念,无论是树的题目还是图的题目,解决的方式一般就是DFS或者是BFS,往里面套就可以了。题目中提到要自底而上,但是这个其实问题不大,只要将自顶而上的列表反转一下就行了。
#python中用deque来实现队列的功能
from collections import deque
def BFS(root):
queue = deque()
wrapList = []
if root is None:
return wrapList
queue.append(root)
while len(queue) != 0:
#发现这个规律是最重要的
levelNum = len(queue)
subList = []
for i in range(levelNum):
node = queue.popleft()
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
subList.append(node.val)
wrapList.insert(0,subList)#实现自底而上
return wrapList
"""
相比于BFS实现,DFS实现有点晦涩
DFS一路向下,自达树的最低层,过程中添加了与树深度相同的子列表
看看递归路径:
3 -> 9
<-
-> 20 -> 15
<-
-> 7
看这路径,就可以发现,竖着看这些数字正好就是我们要的结果。
"""
def DFS(root):
wrapList = []
def level(root,l):
if root is None:
return
if l >= len(wrapList):
wrapList.insert(0,[])
level(root.left,l+1)
level(root.right,l+1)
wrapList[len(wrapList)-l-1].append(root.val)
level(root,0)
return wrapList