Binary Tree Construction from Parent Array

Construct a binary tree from a given array called parent where the parent-child relationship is determined by (PARENT[i], i), indicating that the parent of node i is given by PARENT[i]. If PARENT[i] is -1, then i is the root of the tree.

Input:

The first line contains an integer 'T', representing the number of test cases. For each test case, the input consists of: The first line contains an integer 'N', representing the size of the parent array. The second line contains 'N' space-separated integers, representing the elements of the parent array.

Output:

For each test case, print the level-order traversal of the constructed binary tree in a single line, with nodes separated by spaces.

Example:

Input:
2
5
1 -1 1 2 2
3
-1 0 0
Output:
1 0 2 3 4
0 1 2

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 3000

Note:

The binary tree must satisfy the following conditions:
- If a node has both left and right children, the left child should be less than the right child.
- If a node has only one child, it should be the left child.
- Multiple binary tree configurations may be possible; you need to follow the conditions specified.

AnswerBot
4mo

Construct a binary tree from a given parent array and perform level-order traversal.

  • Iterate through the parent array to create the binary tree using a queue data structure.

  • Keep track of the parent-chi...read more

Help your peers!
Select
Add answer anonymously...

SAP Senior Software Developer interview questions & answers

A Senior Software Developer was asked Q. What is C++?
A Senior Software Developer was asked Q. What is the difference between deep copy and shallow copy?
A Senior Software Developer was asked Q. What is the total number of squares on a chessboard?

Popular interview questions of Senior Software Developer

A Senior Software Developer was asked Q1. What is C++?
A Senior Software Developer was asked Q2. What is the difference between deep copy and shallow copy?
A Senior Software Developer was asked Q3. What is the total number of squares on a chessboard?
SAP Senior 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