Cousin Nodes in a Binary Tree

Determine if two nodes in a binary tree are cousins. Nodes are considered cousins if they are at the same level and have different parents.

Explanation:

In a binary tree, each node has a value, and each tree node has at most two children. Nodes are on the same level if their distance from the root is the same. To be cousins, nodes must also have different parents.

Input:

The first line contains an integer 'T' representing the number of test cases.
For each test case, the first line contains tree elements in level-order, separated by spaces.
The second line contains two space-separated integers representing node values to be checked.

Output:

For each test case, return "YES" if the nodes are cousins, "NO" otherwise.

Example:

Input:
2
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
4 7
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
3 5
Output:
YES
NO
Explanation:

In the first test case, nodes 4 and 7 are cousins as they are on the same level and have different parents. In the second test case, nodes 3 and 5 are not cousins as they do not meet the criteria.

Constraints:

  • 1 ≤ T ≤ 100
  • 1 ≤ N ≤ 1000
  • -10^6 ≤ data ≤ 10^6
  • All nodes have distinct values.
  • -1 represents a null node.
  • Time Limit: 1 sec

Note:

The input for each test case is a single line of integers in level order, where -1 represents a null position.

Be the first one to answer
Add answer anonymously...
Paytm Full Stack 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