Find if two nodes are cousins in Binary Tree

We say two nodes in a binary tree are cousins if they are on same level but have different parents

Algorithm:

  1. Find the parent nodes and levels of the given nodes
  2. Store these in a pair to compare
  3. If they happen to have different parents and same level, then they are cousins, else they are not!

The code should be self explanatory.

Thanks for Reading!!1

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store