@@ -0,0 +1,1723 @@
+package com.interview.tree;%0A%0Aimport java.util.Deque;%0Aimport java.util.LinkedList;%0A%0A/**%0A * http://www.geeksforgeeks.org/check-two-nodes-cousins-binary-tree/%0A * Assumption that both a and b are unique in tree.%0A * Test cases:%0A * Empty tree%0A * Tree with only root%0A * Tree and input with a and b as cousin node%0A * Tree and input with a and b not cousin node%0A */%0Apublic class CousinNodes %7B%0A%0A%09public boolean areCousins(Node root,int a, int b)%7B%0A%09%09Deque%3CNode%3E queue = new LinkedList%3CNode%3E();%0A%09%09queue.offerFirst(root);%0A%09%09int levelSize=1;%0A%09%09int tempLevelSize = 1;%0A%09%09boolean foundFirst = false;%0A%09%09while(!queue.isEmpty())%7B%0A%09%09%09levelSize = 0;%0A%09%09%09while(tempLevelSize %3E 0)%7B%0A%09%09%09%09Node node = queue.pollLast();%0A%09%09%09%09if(node.data == a %7C%7C node.data == b)%7B%0A%09%09%09%09%09if(foundFirst)%7B%0A%09%09%09%09%09%09return true;%0A%09%09%09%09%09%7D%0A%09%09%09%09%09foundFirst = true;%0A%09%09%09%09%7D%0A%09%09%09%09if(node.left!=null)%7B%0A%09%09%09%09%09queue.offerFirst(node.left);%0A%09%09%09%09%09levelSize++;%0A%09%09%09%09%7D%0A%09%09%09%09if(node.right != null)%7B%0A%09%09%09%09%09queue.offerFirst(node.right);%0A%09%09%09%09%09levelSize++;%0A%09%09%09%09%7D%0A%09%09%09%09tempLevelSize--;%0A%09%09%09%7D%0A%09%09%09if(foundFirst)%7B%0A%09%09%09%09return false;%0A%09%09%09%7D%0A%09%09%09tempLevelSize = levelSize;%0A%09%09%7D%0A%09%09return false;%0A%09%7D%0A%09%0A%09public static void main(String args%5B%5D)%7B%0A%09%09BinaryTree bt = new BinaryTree();%0A%09%09Node head = null;%0A%09%09head = bt.addNode(10, head);%0A%09%09head = bt.addNode(15, head);%0A%09%09head = bt.addNode(5, head);%0A%09%09head = bt.addNode(7, head);%0A%09%09head = bt.addNode(19, head);%0A%09%09head = bt.addNode(20, head);%0A%09%09head = bt.addNode(-1, head);%0A%09%09head = bt.addNode(21, head);%0A%09%09head = bt.addNode(-6, head);%0A%09%09CousinNodes cn = new CousinNodes();%0A%09%09System.out.println(cn.areCousins(head, 10, 19));%0A%09%09System.out.println(cn.areCousins(head, 19, 7));%0A%09%09System.out.println(cn.areCousins(head, 19, -1));%0A%09%09System.out.println(cn.areCousins(head, 19, -6));%0A%09%7D%0A%7D%0A

Check if two nodes are cousins