반응형
# 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.
반응형
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 116. Populating Next Right Pointers in Each Node (0) | 2020.12.31 |
---|---|
[LeetCode][Python3] 111. Minimum Depth of Binary Tree (0) | 2020.12.31 |
[LeetCode][Python3] 103. Binary Tree Zigzag Level Order Traversal (0) | 2020.12.31 |
[LeetCode][Python3] 104. Maximum Depth of Binary Tree (0) | 2020.12.28 |
[LeetCode][Python3] 100. Same Tree (0) | 2020.12.28 |