算法-二叉树解题

题目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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值