leetcode 107. Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree [3,9,20,null,null,15,7],

   3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

这个题的解法和leetcode102类似

在这题中基本是在leetcode102的基础上,添加python上的reverse()就行。

python代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
        a = []
        nums = []
        a.append(root)
        if not root:
            return []
        while len(a):
            num = []
            length = len(a)
            for i in range(length):
                T = a[0]
                a.pop(0)
                num.append(T.val)
                if T.left:
                    a.append(T.left)
                if T.right:
                    a.append(T.right)
            nums.append(num)
        nums.reverse()
        return nums
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容