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.
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
Top SAP Senior Software Developer interview questions & answers
Popular interview questions of Senior Software Developer
Top HR questions asked in SAP Senior Software Developer
Reviews
Interviews
Salaries
Users/Month