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.
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
Top Tower Research Capital LLC Software Developer interview questions & answers
Popular interview questions of Software Developer
Reviews
Interviews
Salaries
Users/Month