Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Binary Tree Zigzag Level Order Traversal

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "103" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between). Example 1: Input: root = [3,9,20,null,null,15,7] Output: [[3],[20,9],[15,7]] Example 2: Input: root = [1] Output: [[1]] Example 3: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0, 2000]. -100 <= Node.val <= 100

Explanation

Here's a solution to the zigzag level order traversal problem:

  • Level-by-Level Traversal: Perform a standard level-order traversal using a queue.
  • Zigzag Alternation: Maintain a boolean variable to track the direction (left-to-right or right-to-left). Reverse the order of nodes at each level when needed.
  • Result Accumulation: Store the nodes' values at each level in a list, and append these lists to the final result.

  • Time Complexity: O(N), where N is the number of nodes in the binary tree.

  • Space Complexity: O(W), where W is the maximum width of the binary tree (which can be O(N) in the worst case).

Code

    from collections import deque
from typing import List, Optional

# 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]]:
        if not root:
            return []

        result = []
        queue = deque([root])
        left_to_right = True

        while queue:
            level_size = len(queue)
            level_values = []

            for _ in range(level_size):
                node = queue.popleft()
                level_values.append(node.val)

                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)

            if not left_to_right:
                level_values.reverse()

            result.append(level_values)
            left_to_right = not left_to_right

        return result

More from this blog

C

Chatmagic blog

2894 posts