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...
Top Software Developer Interview Questions Asked at Tower Research Capital LLC
Q. Design an application similar to MakeMyTrip.
Q. Counting Nodes in a Complete Binary Tree - Problem Statement Given the root of a...read more
Q. Unweighted Graph Shortest Path Problem You are tasked with finding the shortest ...read more
Interview Questions Asked to Software Developer at Other Companies
Top Skill-Based Questions for Tower Research Capital LLC Software Developer
Algorithms Interview Questions and Answers
250 Questions
Data Structures Interview Questions and Answers
250 Questions
Web Development Interview Questions and Answers
250 Questions
Java Interview Questions and Answers
250 Questions
SQL Interview Questions and Answers
250 Questions
Software Development Interview Questions and Answers
250 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

