Construct Binary Tree from Parent Array Representation

Given an array parent which represents a binary tree, the parent-child relationship is defined by (PARENT[i], i), meaning that the parent of i is PARENT[i]. The root node's value will be i if -1 is present at PARENT[i].

Example:

Input:
parent = {1, -1, 1}
Output:
1 0 2
Explanation:

As, parent of 0 is PARENT[0] i.e. 1. 1 is the root as PARENT[1] = -1. Parent of 2 is PARENT[2] i.e. 1.

Constraints:

  • 1 ≤ T ≤ 100
  • 1 ≤ N ≤ 3000
  • Time limit: 1 sec.

Note:

From the parent array, multiple binary trees may be possible. You have to create a binary tree in such a way that these conditions satisfy:

  • If the node has a left child as well as a right child, ensure the left child is smaller than the right child.
  • If the node has only one child, it should be the left child.
Example Input:
parent = {1, -1, 1}
Example Output:
1 0 2
Input:
2
3
1 -1 1
3
1 2 -1
Output:
1 0 2
2 1 0
AnswerBot
4mo

Construct a binary tree from parent array representation ensuring specific conditions are met.

  • Iterate through the parent array to create the binary tree

  • Handle cases where a node has both left and righ...read more

Help your peers!
Select
Add answer anonymously...

Traveloka Software Developer interview questions & answers

A Software Developer was asked Q. Search Element in a Rotated Sorted Array Given a sorted array that has been rota...read more
A Software Developer was asked Q. Partition Equal Subset Sum Problem Given an array ARR consisting of 'N' positive...read more
A Software Developer was asked Q. Maximum Path Sum in a Matrix Given an N*M matrix filled with integer numbers, de...read more

Popular interview questions of Software Developer

A Software Developer was asked Q1. Search Element in a Rotated Sorted Array Given a sorted array that has been rota...read more
A Software Developer was asked Q2. Partition Equal Subset Sum Problem Given an array ARR consisting of 'N' positive...read more
A Software Developer was asked Q3. Maximum Path Sum in a Matrix Given an N*M matrix filled with integer numbers, de...read more
Traveloka 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