KatInterview

103. Binary Tree Zigzag Level Order Traversal

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Breadth-First Search (BFS)

This problem is a variation of the standard Binary Tree Level Order Traversal. The key difference is the requirement to traverse levels in a zigzag pattern: left-to-right for the first level, right-to-left for the second, left-to-right for the third, and so on.

Solution

Binary Tree Zigzag Level Order Traversal in Python

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

        result = []
        # Use deque for efficient appends and pops from both ends.
        queue = deque([root])
        left_to_right = True

        while queue:
            level_size = len(queue)
            # Use another deque to build the current level list.
            # append (add to right) and appendleft (add to left) are O(1).
            current_level = deque()

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

                if left_to_right:
                    current_level.append(node.val)
                else:
                    current_level.appendleft(node.val)

                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            
            result.append(list(current_level))
            # Flip the direction for the next level
            left_to_right = not left_to_right
            
        return result

Binary Tree Zigzag Level Order Traversal in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean leftToRight = true;

        while (!queue.isEmpty()) {
            int levelSize = queue.size();
            // Use LinkedList as a Deque for efficient additions at both ends.
            LinkedList<Integer> currentLevel = new LinkedList<>();

            for (int i = 0; i < levelSize; i++) {
                TreeNode node = queue.poll();

                // Add to the list based on the current direction
                if (leftToRight) {
                    currentLevel.addLast(node.val);
                } else {
                    currentLevel.addFirst(node.val);
                }

                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            
            result.add(currentLevel);
            // Flip the direction for the next level
            leftToRight = !leftToRight;
        }

        return result;
    }
}

Binary Tree Zigzag Level Order Traversal in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        if (!root) {
            return {};
        }

        vector<vector<int>> result;
        queue<TreeNode*> q;
        q.push(root);
        bool leftToRight = true;

        while (!q.empty()) {
            int levelSize = q.size();
            // Pre-allocate vector for the current level's nodes
            vector<int> currentLevel(levelSize);

            for (int i = 0; i < levelSize; ++i) {
                TreeNode* node = q.front();
                q.pop();

                // Determine the correct index to insert the value based on direction
                int index = leftToRight ? i : (levelSize - 1 - i);
                currentLevel[index] = node->val;

                if (node->left) {
                    q.push(node->left);
                }
                if (node->right) {
                    q.push(node->right);
                }
            }

            result.push_back(currentLevel);
            // Flip the direction for the next level
            leftToRight = !leftToRight;
        }

        return result;
    }
};

Binary Tree Zigzag Level Order Traversal in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function zigzagLevelOrder(root: TreeNode | null): number[][] {
    if (!root) {
        return [];
    }

    const result: number[][] = [];
    // Use a simple array as a queue and a pointer to manage the front.
    // This avoids the O(n) cost of array.shift().
    const queue: TreeNode[] = [root];
    let head = 0;
    let leftToRight = true;

    // Loop while there are still nodes to process.
    while (head < queue.length) {
        const levelSize = queue.length - head; // Number of nodes at the current level.
        const currentLevel: number[] = new Array(levelSize);

        for (let i = 0; i < levelSize; i++) {
            const node = queue[head++]; // Dequeue the node.

            // Determine the correct index to place the node's value for zigzag order.
            const index = leftToRight ? i : (levelSize - 1 - i);
            currentLevel[index] = node.val;

            // Enqueue children.
            if (node.left) {
                queue.push(node.left);
            }
            if (node.right) {
                queue.push(node.right);
            }
        }

        result.push(currentLevel);
        // Flip the direction for the next level.
        leftToRight = !leftToRight;
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.