Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Cousins of Given Node in Binary Tree

Moderate
0/80
Average time to solve is 10m
profile
Contributed by
11 upvotes
Asked in companies
FlipkartPaytm (One97 Communications Limited)Samsung

Problem statement

Given a binary tree of N nodes and a node of this tree, you need to return a list containing the values of the cousins of the given node in the given binary tree sorted by non-decreasing order of their values.

Note:
Two nodes of a binary tree are cousins if they have the same depth or level, but have different parents.

No two nodes in the given binary tree will have the same data values.
Example :

Example Of Cousins

Detailed explanation ( Input/output format, Notes, Images )
Constraints:
1 <= T <= 100
1 <= N <= 3000
1 <= nodeVal <= 10^9

Time Limit: 1 sec
Sample Input 1 :
2
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
4
1 2 3 -1 -1 -1 -1
2 
Sample Output 1 :
5 6
-1
Explanation For Sample Input 1 :
The tree representation for test case 2 is given below.

Sample Test case 2

Sample Input 2 :
2
1 2 3 4 5 6 -1 7 8 -1 -1 9 10 -1 -1 -1 -1 -1 -1 -1 -1
9   
1 2 -1 3 4 -1 -1 -1 -1
3
Sample Output 2 :
7 8 10
-1
Full screen
Console