|
| 1 | +package com.interview.tree; |
| 2 | + |
| 3 | +import java.util.Deque; |
| 4 | +import java.util.LinkedList; |
| 5 | + |
| 6 | +/** |
| 7 | + * http://www.geeksforgeeks.org/check-two-nodes-cousins-binary-tree/ |
| 8 | + * Assumption that both a and b are unique in tree. |
| 9 | + * Test cases: |
| 10 | + * Empty tree |
| 11 | + * Tree with only root |
| 12 | + * Tree and input with a and b as cousin node |
| 13 | + * Tree and input with a and b not cousin node |
| 14 | + */ |
| 15 | +public class CousinNodes { |
| 16 | + |
| 17 | + public boolean areCousins(Node root,int a, int b){ |
| 18 | + Deque<Node> queue = new LinkedList<Node>(); |
| 19 | + queue.offerFirst(root); |
| 20 | + int levelSize=1; |
| 21 | + int tempLevelSize = 1; |
| 22 | + boolean foundFirst = false; |
| 23 | + while(!queue.isEmpty()){ |
| 24 | + levelSize = 0; |
| 25 | + while(tempLevelSize > 0){ |
| 26 | + Node node = queue.pollLast(); |
| 27 | + if(node.data == a || node.data == b){ |
| 28 | + if(foundFirst){ |
| 29 | + return true; |
| 30 | + } |
| 31 | + foundFirst = true; |
| 32 | + } |
| 33 | + if(node.left!=null){ |
| 34 | + queue.offerFirst(node.left); |
| 35 | + levelSize++; |
| 36 | + } |
| 37 | + if(node.right != null){ |
| 38 | + queue.offerFirst(node.right); |
| 39 | + levelSize++; |
| 40 | + } |
| 41 | + tempLevelSize--; |
| 42 | + } |
| 43 | + if(foundFirst){ |
| 44 | + return false; |
| 45 | + } |
| 46 | + tempLevelSize = levelSize; |
| 47 | + } |
| 48 | + return false; |
| 49 | + } |
| 50 | + |
| 51 | + public static void main(String args[]){ |
| 52 | + BinaryTree bt = new BinaryTree(); |
| 53 | + Node head = null; |
| 54 | + head = bt.addNode(10, head); |
| 55 | + head = bt.addNode(15, head); |
| 56 | + head = bt.addNode(5, head); |
| 57 | + head = bt.addNode(7, head); |
| 58 | + head = bt.addNode(19, head); |
| 59 | + head = bt.addNode(20, head); |
| 60 | + head = bt.addNode(-1, head); |
| 61 | + head = bt.addNode(21, head); |
| 62 | + head = bt.addNode(-6, head); |
| 63 | + CousinNodes cn = new CousinNodes(); |
| 64 | + System.out.println(cn.areCousins(head, 10, 19)); |
| 65 | + System.out.println(cn.areCousins(head, 19, 7)); |
| 66 | + System.out.println(cn.areCousins(head, 19, -1)); |
| 67 | + System.out.println(cn.areCousins(head, 19, -6)); |
| 68 | + } |
| 69 | +} |
0 commit comments