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
3d
Given a binary tree and a specific node, return a sorted list of the values 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...read more
Help your peers!
Add answer anonymously...
Top Samsung Frontend Developer Intern interview questions & answers
Popular interview questions of Frontend Developer Intern
Stay ahead in your career. Get AmbitionBox app
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
Get AmbitionBox app