算法-二叉树解题

来源:互联网 发布:淘宝客服昵称大全男 编辑:程序博客网 时间:2024/06/05 11:30

题目1:Leecode-107

给定一个二叉树,从左向右地,自底向上的遍历每一层的元素。

例:给定二叉树:            3          /  \         9   20            /  \           15   7返回的结果:[    [15,7],    [9,20],    [3]]

首先,要有一个概念,无论是树的题目还是图的题目,解决的方式一般就是DFS或者是BFS,往里面套就可以了。题目中提到要自底而上,但是这个其实问题不大,只要将自顶而上的列表反转一下就行了。

#python中用deque来实现队列的功能from collections import dequedef 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
原创粉丝点击