Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

In a Binary Tree, Check if two nodes are Cousins

Objec­tive: 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 par­ents are siblings.

Exam­ple:

Cousin Nodes

Cousin Nodes

Approach:

  • Check the height of both the nodes, if heights are dif­fer­ent then return false.
  • Check if both the nodes has the same par­ent, if yes then return false.
  • else return true.

Com­plete Code:


Out­put:

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

You may also like...