Cousins of a Given Node in a Binary Tree
Given a binary tree with 'N' nodes and a specific node in this tree, you need to determine and return a sorted list of the values of the node's cousins. The cousins should be sorted in non-decreasing order based on their values.
Definition:
In a binary tree, two nodes are considered cousins if they are at the same depth or level but have different parent nodes.
Note:
-
This tree setup has unique data values; hence no two nodes will have identical values.
Input:
The input starts with a single integer T, representing the number of test cases.
For each test case:
- The first line consists of node values of the binary tree provided in level order format (use -1 for NULL nodes).
- The second line provides the specific node value for which cousins need to be identified.
Output:
- For each test case, return the sorted list of cousin node values.
- If the node has no cousins, return -1.
Example:
Consider a binary tree:
Input:
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
7
Output:
[5, 6]
Explanation: For the node with value 7, the cousins at the same level are 5 and 6.
Constraints:
- 1 <= T <= 100
- 1 <= N <= 3000
- 1 <= nodeVal <= 109
- Time Limit: 1 second

AnswerBot
4mo
Given a binary tree and a specific node, return a sorted list of the node's cousins.
Traverse the binary tree to find the parent of the given node and its depth.
Traverse the tree again to find nodes at...read more
Help your peers!
Add answer anonymously...
Samsung Software Developer Intern interview questions & answers
A Software Developer Intern was asked 7mo agoQ. Suppose an array of length n sorted in ascending order is rotated between 1 and ...read more
A Software Developer Intern was asked 7mo agoQ. What are the ACID properties in DBMS?
A Software Developer Intern was asked Q. Sum of Digits Problem Statement Given an integer 'N', continue summing its digit...read more
Popular interview questions of Software Developer Intern
A Software Developer Intern was asked 6mo agoQ1. Suppose an array of length n sorted in ascending order is rotated between 1 and ...read more
A Software Developer Intern was asked 6mo agoQ2. What are the ACID properties in DBMS?
A Software Developer Intern was asked Q3. Sum of Digits Problem Statement Given an integer 'N', continue summing its digit...read more
Stay ahead in your career. Get AmbitionBox app


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
AmbitionBox Awards
Get AmbitionBox app

