Check If Two Nodes Are Cousins
You are given an arbitrary binary tree consisting of N nodes, where each node is associated with a certain value, and two node values, a
and b
. Your task is to determine if these nodes are cousins.
Two nodes are cousins if they are at the same level in the tree and have different parents. Nodes at the same level are equidistant from the root node.
Example:
Input:
The given tree in level order:
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Two node values:
4 7
Output:
YES
Explanation:
Nodes 4 and 7 are at the same level with different parents, hence they are cousins.
Input Format:
The first line contains an integer 'T' denoting the number of test cases. Each test case consists of two parts:
1. A single line with tree elements in level order, separated by spaces. Use -1 to represent null nodes.
2. A single line with two space-separated integers which are the values of the nodes in the binary tree.
Output Format:
For each test case, return “YES” if the given two nodes are cousins and “NO” otherwise (return without the quotes).
Constraints:
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 1000
- -106 ≤ data ≤ 106 and data ≠ -1
- The Binary Tree has only distinct elements.
- Time Limit: 1 sec
Note:
No output needs to be printed. Implement the function to solve the problem.

AnswerBot
4mo
Check if two nodes in a binary tree are cousins by comparing their levels and parents.
Traverse the tree to find the levels and parents of the given nodes.
Compare the levels and parents of the two node...read more
Help your peers!
Add answer anonymously...
Tower Research Capital LLC Software Developer interview questions & answers
A Software Developer was asked 9mo agoQ. Design an application similar to MakeMyTrip.
A Software Developer was asked Q. Check If Two Nodes Are Cousins You are given an arbitrary binary tree consisting...read more
A Software Developer was asked Q. Counting Nodes in a Complete Binary Tree - Problem Statement Given the root of a...read more
Popular interview questions of Software Developer
A Software Developer was asked 9mo agoQ1. Design an application similar to MakeMyTrip.
A Software Developer was asked Q2. Check If Two Nodes Are Cousins You are given an arbitrary binary tree consisting...read more
A Software Developer was asked Q3. Counting Nodes in a Complete Binary Tree - Problem Statement Given the root of a...read more
>
Tower Research Capital LLC Software Developer Interview Questions
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

