码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 107. Binary Tree Level Order Traversal II

时间:2021-03-15 11:13:18      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:put   continue   none   obj   pap   ret   lazy   turn   man   

Description: Given the root of a binary tree, return the bottom-up level order traversal of its nodes‘ values. (i.e., from left to right, level by level from leaf to root).

Link: 107. Binary Tree Level Order Traversal II

Exaples:

Example 1:
技术图片
Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]

Example 2:
Input: root = [1]
Output: [[1]]

Example 3:
Input: root = []
Output: []

思路: 因为是按照每一层返回,所以用广搜,BFS每一层的val,然后reverse list返回。

class Solution(object):
    def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if root is None: return []
        res = []
        que = collections.deque()
        que.append(root)
        while que:
            size = len(que)
            layerval = []
            for _ in range(size):
                node = que.popleft()
                if node is None:
                    continue
                layerval.append(node.val)
                que.append(node.left)
                que.append(node.right)
            if len(layerval)>0:
                res.append(layerval)
        return res[::-1]

日期: 2021-03-13 (Peer presure is so heavy, many papers are accepted in our group by NAACL, feel so stressed.)

Leetcode 107. Binary Tree Level Order Traversal II

标签:put   continue   none   obj   pap   ret   lazy   turn   man   

原文地址:https://www.cnblogs.com/wangyuxia/p/14528887.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!