美文网首页
107. Binary Tree Level Order Tra

107. Binary Tree Level Order Tra

作者: 羲牧 | 来源:发表于2020-06-14 16:21 被阅读0次

    其实和102. Binary Tree Level Order Traversal这题几乎一样的思路和解法。
    不赘述,直接给代码。

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
            result = []
            if root is None:
                return result
            
            queue = [root]
            while len(queue):
                length = len(queue)
                level = []
                for i in range(length):
                    p = queue.pop(0)
                    level.append(p.val)
                    if p.left:
                        queue.append(p.left)
                    if p.right:
                        queue.append(p.right)
                result.insert(0, level)
            return result
                
            
    

    相关文章

      网友评论

          本文标题:107. Binary Tree Level Order Tra

          本文链接:https://www.haomeiwen.com/subject/olaxxktx.html