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
7d

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!
Add answer anonymously...
SAP Senior Software Developer 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