zoukankan      html  css  js  c++  java
  • Leetcode 107. Binary Tree Level Order Traversal II

    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.)

  • 相关阅读:
    2021年2月13
    2021年2月12
    2021年2月11
    2021年2月10
    2021年2月9
    下载优化
    20180301越努力越轻松
    2018-03-01继续完善2
    2018-03-01继续完善
    2018-02-16 GetSameTypeQuestion
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14528887.html
Copyright © 2011-2022 走看看