Asked inPubMatic,SDE-2

Binary Tree Zigzag Traversal Problem Statement

Given a Binary Tree comprised of 'N' nodes with integer values, your task is to print the zigzag traversal of the tree.

Note:

The zigzag pattern implies that the first level is traversed from left to right, the second level from right to left, and this pattern continues alternately for subsequent levels.

Example:

Input:
The following binary tree: 
Binary Tree
Output:
[1, 4, 3, 5, 2, 7, 6]

Input:

The first line contains an integer 'T' representing the number of test cases. For each test case, the input follows: 
The line contains elements of the tree in level order form, with values of nodes separated by spaces. Use -1 for null nodes.

Example:
1 3 8 5 2 7 -1 -1 -1 -1 -1 -1 -1

Output:

For each test case, print the zigzag order traversal of nodes in a single line, with values separated by spaces.

Constraints:

  • 1 <= 'T' <= 100
  • 0 <= 'N' <= 10^3
  • 0 <= 'NODES' <= 10^9

You do not need to handle input/output in your solution. Implement the function as directed.

Be the first one to answer
Add answer anonymously...
PubMatic SDE-2 Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

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

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter