본문 바로가기

Algorithm/LeetCode

[LeetCode][Python3] 107. Binary Tree Level Order Traversal II

반응형
# 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]]:
        queue = []
        answer = []
        if not root: return []
        queue.append(root)
        while(len(queue)!=0):
            floor=[]
            for _ in range(0,len(queue)):

                node = queue.pop(0)
                if node.left !=None: queue.append(node.left)
                if node.right !=None: queue.append(node.right)
                floor.append(node.val)
            answer.append(floor)
        return answer[::-1]

여러가지 방법이 있겠지만 이 방법이 가장 효율적인 것 같다.

Runtime: 28 ms, faster than 94.48% of Python3 online submissions for Binary Tree Level Order Traversal II.
Memory Usage: 14.5 MB, less than 71.78% of Python3 online submissions for Binary Tree Level Order Traversal II.
반응형