반응형
풀이
queue에 들어있는 node들은 같은 level입니다. 따라서 현재 queue의 node들을 꺼내 list에 넣어주고, node의 left와 right node들은 queue에 새로 넣어줍니다.
# 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 levelOrder(self, root: TreeNode) -> List[List[int]]:
queue = []
answer = []
level = []
if not root: return []
queue.append(root)
while(len(queue)!=0):
level.clear()
for _ in range(0,len(queue)):
node = queue.pop(0)
level.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
answer.append(level.copy())
return answer
반응형
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 104. Maximum Depth of Binary Tree (0) | 2020.12.28 |
---|---|
[LeetCode][Python3] 100. Same Tree (0) | 2020.12.28 |
[LeetCode][Python3] 98. Validate Binary Search Tree (0) | 2020.12.27 |
[LeetCode][Python3] 17. Letter Combinations of a Phone Number (0) | 2020.12.27 |
[LeetCode][Python3] 21. Merge Two Sorted Lists (0) | 2020.12.26 |