103 - Zigzag Level Order Traversal of BT

mail@pastecode.io avatar
unknown
python
a month ago
1.3 kB
5
Indexable
Never
# 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

from collections import deque
class Solution:
    def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:

        if root is None:
            return []
        result_list = []
        level_tracker = 0

        q = deque([root])

        while len(q) > 0:
            current_breadth_nodes = []
            # iterate through the queue, pack all nodes at the current breadth/frontier into the list
            for _ in range(len(q)):
                u = q.popleft()
                current_breadth_nodes.append(u.val)
                if u.left is not None:
                    q.append(u.left)
                if u.right is not None:
                    q.append(u.right)
            if level_tracker % 2 == 0:
                result_list.append(current_breadth_nodes)
            else:
                current_breadth_nodes_reversed = current_breadth_nodes[::-1]
                result_list.append(current_breadth_nodes_reversed)
            level_tracker += 1
        
        return result_list
            




        
Leave a Comment