In a Binary Tree, Check if Two nodes has the same parent or are siblings

Objective: In a Binary Tree, Check if Two nodes has the same parent or are siblings

Input: A binary tree and two nodes

Example:

Siblings Nodes

Approach:

  • Given, root, Node x, Node y.
  • Check if x and y are childs of root. (root.left==x && root.right==y) ||root.left==y && root.right==x)
  • if yes then return true.
  • Else make a recursive call to root.left and root.right

Complete Code:


Output:

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

__________________________________________________
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.
__________________________________________________

You may also like...

%d bloggers like this: