Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // program to print if 2 nodes of a binary tree are cousins or not
- /**
- * Created by MOHIT on 25-05-2018.
- */
- import java.io.*;
- import java.util.*;
- import static java.lang.Integer.max;
- // node class
- class node{
- int data;
- node left;
- node right;
- // function that returns a pointer to new node
- public node(int element){
- this.data = element;
- this.left = null;
- this.right = null;
- }
- };
- public class BinaryTree {
- static int level_of_node(node root, int data){
- return level_of_node_helper(root, data, -1);
- }
- // function to find and return the level of a node in binary tree
- static int level_of_node_helper(node root, int data, int level){
- // if the tree is isEmpty or if we reach a leaf node then return 0
- if (root == null){
- return -1;
- }
- if(root.data == data){
- return level+1;
- }
- // check in the left subtree for the element
- // if found then return the level
- int level_node = level_of_node_helper(root.left, data, level + 1);
- if (level_node != -1){
- return level_node;
- }
- // searching for the node in right subtree
- level_node = level_of_node_helper(root.right, data, level + 1);
- return level_node;
- }
- // function to check if 2 nodes are siblings or not
- static boolean isSibling(node parent, int n1, int n2){
- if(parent == null){
- return false;
- }
- if(parent.left != null && parent.right != null) {
- return (parent.left.data == n1 && parent.right.data == n2) ||
- (parent.left.data == n2 && parent.right.data == n1);
- }
- return (isSibling(parent.left, n1, n2) || isSibling(parent.right, n1, n2));
- }
- static boolean isCousin(node root, int a, int b){
- if( (level_of_node(root, a) == level_of_node(root, b) && isSibling(root, a, b))){
- return true;
- }
- return false;
- }
- public static void main(String arg[]) {
- node head = new node(1);
- head.left = new node(2);
- head.right = new node(3);
- head.left.left = new node(4);
- head.left.right = new node(5);
- head.right.right = new node(6);
- head.left.left.right = new node(7);
- head.right.right.left = new node(8);
- head.left.left.right.left = new node(9);
- head.left.left.right.left.left = new node(10);
- head.right.right.left.right = new node(11);
- System.out.println("Nodes 2 and 3 are siblings : " + isCousin(head, 2, 3));
- System.out.println("Nodes 6 and 10 are siblings : " + isCousin(head, 6, 10));
- System.out.println("Nodes 7 and 8 are siblings : " + isCousin(head, 7, 8));
- }
- }
Add Comment
Please, Sign In to add comment