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 has the same parent or are siblings

Objec­tive: In a Binary Tree, Check if Two nodes has the same par­ent or are siblings

Input: A binary tree and two nodes

Exam­ple:

Siblings Nodes

Sib­lings 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 recur­sive call to root.left and root.right

Com­plete Code:


Out­put:

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

You may also like...