LeetCode 103. Binary Tree Zigzag Level Order Traversal

Description

https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/

Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

Explanation

level order traverse and reverse the result at odd level.

Python Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        result = []
        
        if root == None:
            return result
        
        queue = []
        queue.append(root)
        
        level_index = 0
        while len(queue) > 0:            
            level = []
            level_size = len(queue)
            
            for i in range(0, level_size):
                node = queue.pop(0)  
                level.append(node.val)
                
                if node.left:
                    queue.append(node.left)                   
                if node.right:
                    queue.append(node.right)      
                        
            
            if level_index % 2 != 0:                    
                level = list(reversed(level))
            
            result.append(level)
            level_index += 1

        return result
  • Time complexity: O(N).
  • Space complexity: O(N).

One Thought to “LeetCode 103. Binary Tree Zigzag Level Order Traversal”

Leave a Reply

Your email address will not be published. Required fields are marked *