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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.