Zigzag Binary Tree Traversal Problem

Given a binary tree, compute the zigzag level order traversal of the node values in the tree. The zigzag traversal requires traversing levels from left to right, then right to left for the next level, and alternating accordingly.

Input:

It starts with an integer 'T', representing the number of test cases. Each test case consists of a single line of space-separated integers representing nodes in level order. If a node is null, it is denoted by -1. The -1 will not be included in the actual nodes.

Output:

For each test case, output the zigzag level order traversal of the binary tree, with values separated by a single space. Print each test case result on a new line.

Example:

Input:
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Output:
1 3 2 4 5 6 7

The example represents a binary tree where, starting from the root, level by level, the output reflects zigzag traversal.

Constraints:

  • 1 <= T <= 100
  • 0 <= N <= 3000
  • 0 <= val <= 105

Where ‘T’ is the number of test cases, ‘N’ is the total number of nodes in the binary tree, and “val” is the value of the binary tree node.

Time Limit: 1 sec

AnswerBot
4mo

Zigzag level order traversal of a binary tree is computed by alternating between left to right and right to left traversal at each level.

  • Use a queue to perform level order traversal of the binary tree...read more

Help your peers!
Select
Add answer anonymously...

Park Plus Software Developer interview questions & answers

A Software Developer was asked 9mo agoQ. Explain hoisting in JavaScript.
A Software Developer was asked 9mo agoQ. Explain closures in JavaScript.
A Software Developer was asked Q. Zigzag Binary Tree Traversal Problem Given a binary tree, compute the zigzag lev...read more

Popular interview questions of Software Developer

A Software Developer was asked 9mo agoQ1. Explain hoisting in JavaScript.
A Software Developer was asked 9mo agoQ2. Explain closures in JavaScript.
A Software Developer was asked Q3. Zigzag Binary Tree Traversal Problem Given a binary tree, compute the zigzag lev...read more
Park Plus Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits