LeetCode/Top Interview 150

103. Binary Tree Zigzag Level Order Traversal

hyunkookim 2024. 12. 15. 18:39

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: Optional[TreeNode]) -> List[List[int]]:
        # bfs => 큐로
        if not root:
            return []

        res = []

        que = deque([root])
        idx = 0
        while que:
            l = len(que)
            sub_res = []
            for i in range(l):
                node = que.popleft()
                sub_res.append(node.val)

                if node.left:
                    que.append(node.left)
                if node.right:
                    que.append(node.right)                
            
            if idx % 2 == 0: # 짝수면 
                res.append(sub_res) # 그대로 추가
            else: # 홀수면 
                res.append(sub_res[::-1]) # 역순으로 추가
            idx = (idx + 1) % 2
        
        return res

'LeetCode > Top Interview 150' 카테고리의 다른 글

67. Add Binary  (0) 2024.12.17
530. Minimum Absolute Difference in BST  (0) 2024.12.15
637. Average of Levels in Binary Tree  (0) 2024.12.14
222. Count Complete Tree Nodes  (0) 2024.12.14
129. Sum Root to Leaf Numbers  (1) 2024.12.13