반응형
# 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 zigzagLevelOrder(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())
for i,lst in enumerate(answer):
if i%2==1:
lst=lst.reverse()
return answer
더 좋은 방법이 많겠지만 저번 코드를 재활용했다.
반응형
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 111. Minimum Depth of Binary Tree (0) | 2020.12.31 |
---|---|
[LeetCode][Python3] 107. Binary Tree Level Order Traversal II (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 |
[LeetCode][Python3] 102. Binary Tree Level Order Traversal (0) | 2020.12.27 |