📖 Scenario: You are working with a binary tree data structure that stores numbers. You want to visit the nodes level by level, but with a twist: the order of visiting nodes alternates between left-to-right and right-to-left for each level. This is called zigzag level order traversal.Imagine you are reading a book where you read the first line left to right, the second line right to left, the third line left to right again, and so on.
🎯 Goal: Build a program in C that performs zigzag level order traversal on a binary tree and prints the values of nodes level by level in the zigzag order.
📋 What You'll Learn
Define a binary tree node structure with integer values
Create a sample binary tree with exact nodes and structure
Implement zigzag level order traversal using a queue and stack or two stacks
Print the nodes level by level in zigzag order
💡 Why This Matters
🌍 Real World
Zigzag traversal is useful in scenarios like printing tree data in a visually appealing way or processing hierarchical data with alternating order.
💼 Career
Understanding tree traversals and queue/stack usage is essential for software engineering roles involving data structures, algorithms, and system design.
Progress0 / 4 steps
1
Create the binary tree structure and sample tree
Define a struct called TreeNode with an int val, and two pointers left and right to TreeNode. Then create a sample binary tree with root node value 1, left child 2, right child 3, left child of 2 as 4, and right child of 2 as 5.
DSA C
Hint
Use a struct with pointers for left and right children. Create a helper function createNode to allocate and initialize nodes.
2
Add queue and stack structures for traversal
Define a simple queue and stack structure to hold TreeNode* pointers. Create arrays and integer variables for front, rear, and top indices. Initialize these structures to be used for the zigzag traversal.
DSA C
Hint
Use arrays of TreeNode* for queue and stack. Use integers to track positions.
3
Implement zigzag level order traversal logic
Write code inside main to perform zigzag level order traversal on the tree root. Use the queue and stack to alternate between left-to-right and right-to-left order for each level. Print the node values separated by spaces for each level, and print a newline after each level.
DSA C
Hint
Use a flag leftToRight to switch direction each level. Use a queue to hold nodes of the current level. For right-to-left, store nodes in a stack and print in reverse order.
4
Print the zigzag traversal output
Add a print statement inside the traversal loop to print the node values separated by spaces for each level, and print a newline after each level. Run the program to display the zigzag level order traversal of the tree.
DSA C
Hint
Make sure to print a newline after each level and spaces between node values.
Practice
(1/5)
1. What does the Zigzag Level Order Traversal of a binary tree do differently compared to a normal level order traversal?
easy
A. It traverses the tree in preorder fashion.
B. It visits nodes only at even levels.
C. It visits nodes in reverse order of their insertion.
D. It alternates the direction of traversal at each level, left to right then right to left.
Solution
Step 1: Understand normal level order traversal
Normal level order traversal visits nodes level by level from left to right.
Step 2: Identify zigzag difference
Zigzag traversal changes direction at each level, so first level left to right, next right to left, and so on.
Final Answer:
It alternates the direction of traversal at each level, left to right then right to left. -> Option D
Quick Check:
Zigzag alternates direction = It alternates the direction of traversal at each level, left to right then right to left. [OK]
Hint: Remember zigzag flips direction each level [OK]
Common Mistakes:
Thinking it only visits even levels
Confusing with preorder traversal
Assuming it visits nodes in insertion order
2. Which of the following C code snippets correctly initializes a queue for level order traversal in Zigzag Level Order Traversal?
easy
A. Queue q; q.front = 0; q.rear = 0;
B. Queue* q = createQueue(); q->front = q->rear = -1;
C. Queue* q; q->front = 0; q->rear = 0;
D. Queue q = NULL; q->front = -1; q->rear = -1;
Solution
Step 1: Understand queue initialization in C
Queue pointer must be assigned memory using createQueue() or malloc before accessing members.
Step 2: Check each option
Queue* q = createQueue(); q->front = q->rear = -1; correctly creates a queue pointer and initializes front and rear to -1. Queue q; q.front = 0; q.rear = 0; uses struct without pointer but does not allocate memory. Queue* q; q->front = 0; q->rear = 0; uses pointer without allocation. Queue q = NULL; q->front = -1; q->rear = -1; assigns NULL to struct variable which is invalid.
Hint: Allocate memory before using pointer members [OK]
Common Mistakes:
Using uninitialized pointers
Assigning NULL to struct variable
Not allocating memory before access
3. Given the binary tree:
1
/ \
2 3
/ \ \
4 5 6
What is the output of Zigzag Level Order Traversal?
medium
A. [[1], [3, 2], [4, 5, 6]]
B. [[1], [2, 3], [6, 5, 4]]
C. [[1], [3, 2], [6, 5, 4]]
D. [[1], [2, 3], [4, 5, 6]]
Solution
Step 1: Traverse level 0 left to right
Level 0 has node 1, so output is [1].
Step 2: Traverse level 1 right to left
Level 1 nodes are 2 and 3. Right to left means [3, 2].
Step 3: Traverse level 2 left to right
Level 2 nodes are 4, 5, 6. Left to right means [4, 5, 6].
Final Answer:
[[1], [3, 2], [4, 5, 6]] -> Option A
Quick Check:
Zigzag order matches [[1], [3, 2], [4, 5, 6]] [OK]
Hint: Alternate direction each level, start left to right [OK]
Common Mistakes:
Not reversing order on alternate levels
Mixing node values order
Confusing left and right children
4. Consider this snippet for Zigzag Level Order Traversal in C:
while (!isEmpty(queue)) {
int size = queueSize(queue);
for (int i = 0; i < size; i++) {
Node* node = dequeue(queue);
if (leftToRight) {
addToResult(node->val);
} else {
addToResultAtFront(node->val);
}
if (node->left) enqueue(queue, node->left);
if (node->right) enqueue(queue, node->right);
}
leftToRight = !leftToRight;
}
What is the main bug in this code?
medium
A. The for loop should run until queue is empty, not fixed size.
B. leftToRight flag is not toggled correctly.
C. Using addToResultAtFront causes inefficient insertion, should use a stack.
D. Nodes are enqueued after processing, should enqueue before.
Solution
Step 1: Analyze insertion method for zigzag
Adding elements at front of a list repeatedly is inefficient; a stack or deque is better for reversing order.
Step 2: Check other parts
leftToRight toggling is correct. Enqueuing children after processing is standard. For loop running fixed size is correct to process current level only.
Final Answer:
Using addToResultAtFront causes inefficient insertion, should use a stack. -> Option C
Quick Check:
Efficient reversal needs stack/deque, not front insertion [OK]
Hint: Use stack or deque for reverse order insertion [OK]
Common Mistakes:
Not toggling direction flag
Enqueuing nodes before processing
Incorrect loop bounds for level size
5. You want to perform Zigzag Level Order Traversal on a binary tree but only print nodes at odd levels (1, 3, 5, ...). Which modification is correct?
hard
A. Add a level counter and print results only when level % 2 == 1.
B. Skip enqueuing nodes at even levels.
C. Toggle leftToRight only on odd levels.
D. Reverse the entire traversal output after completion.
Solution
Step 1: Track current level number
Maintain a counter for levels starting at 1 for root level.
Step 2: Print only odd levels
When processing each level, print or store nodes only if level number is odd (level % 2 == 1).
Step 3: Keep traversal logic unchanged
Enqueue all children normally and toggle direction each level to maintain zigzag pattern.
Final Answer:
Add a level counter and print results only when level % 2 == 1. -> Option A
Quick Check:
Filter output by odd levels using counter [OK]
Hint: Use level counter and print only odd levels [OK]
Common Mistakes:
Skipping enqueuing nodes breaks traversal
Toggling direction only on odd levels breaks zigzag
Reversing output after traversal is incorrect
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.