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.

Be the first one to answer
Add answer anonymously...
Tower Research Capital LLC Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
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

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter