In a Binary Tree, Check if two nodes are Cousins

Objective: Given a binary tree and two nodes, Check if they are cousins

Input: A binary tree and two nodes

Cousin Nodes: Cousin nodes are the nodes who are at the same level in the tree and whose parents are siblings.

Example:

Cousin Nodes

Approach:

  • Check the height of both the nodes, if heights are different then return false.
  • Check if both the nodes has the same parent, if yes then return false.
  • else return true.

Complete Code:

Output:

Node 2 and Node 3 are cousins??? false
Node 7 and Node 9 are cousins??? true

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

%d bloggers like this: