본문 바로가기

Algorithm/LeetCode

[LeetCode][Python3] 103. Binary Tree Zigzag 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 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

                    

더 좋은 방법이 많겠지만 저번 코드를 재활용했다.

반응형