Familiarisation of java lists

Posted On // Leave a Comment

 What are Lists?


The java.util.List interface is a subtype of the java.util.Collection interface.
The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements.
  • Elements can be inserted or accessed by their position in the list, using a zero-based index.
  • A list may contain duplicate elements.
  • In addition to the methods defined by Collection, List defines some of its own, which are summarized in the following below Table.
  • Several of the list methods will throw an UnsupportedOperationException if the collection cannot be modified, and a ClassCastException is generated when one object is incompatible with another.



How to initialise?


Since List is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following List implementations in the Java Collections API:
  • java.util.ArrayList
  • java.util.LinkedList
  • java.util.Vector
  • java.util.Stack
We can instantiate lists with above as:

List<E> AL = new ArrayList<>();
List<E> LL= new LinkedList<>();
List<E> V = new Vector<>();
List<E> S = new Stack<>();

We should give the generic class otherwise there would be unchecked/unsafe operation error. generic classes can be any predefined or user defined classes.

As with standard linked list and array operations, the various methods will have different algorithmic runtimes.
For LinkedList<E>
  • get(int index) is O(n)
  • add(E element) is O(1)
  • add(int index, E element) is O(n)
  • remove(int index) is O(n)
  • Iterator.remove() is O(1) <--- main benefit of LinkedList<E>
  • ListIterator.add(E element) is O(1) <--- main benefit of LinkedList<E>
For ArrayList<E>
  • get(int index) is O(1) <--- main benefit of ArrayList<E>
  • add(E element) is O(1) amortized, but O(n) worst-case since the array must be resized and copied
  • add(int index, E element) is O(n - index) amortized, but O(n) worst-case (as above)
  • remove(int index) is O(n - index) (i.e. removing last is O(1))
  • Iterator.remove() is O(n - index)
  • ListIterator.add(E element) is O(n - index)

How to add elements?


List interface supports these functions for adding elements
  • void add(E obj)
  Adds objects to the end of the list.
  • void add(int index,E obj)  
          Inserts obj into the invoking list at the index passed in index. Any pre-existing elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten.
  • boolean addAll(int index, Collection c)
          Inserts all elements of c into the invoking list at the index passed in index. Any pre-existing elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten. Returns true if the invoking list changes and returns false otherwise.

 Here are a few examples:

List<Integer> AL = new ArrayList<>();
AL.add(0);
AL.add(5);//adding elements at the end of list
AL.add(1,4);// adding elements at a specified index
List<Integer> tmp = new LinkedList<>();
tmp.add(1);
tmp.add(2);
tmp.add(3);
AL.addAll(1,tmp);// adding an another collection

System.out.println(AL);
//Now the above statement yields output
[0, 1, 2, 3, 4, 5]


How to access elements?

The functions used to access elements are:
  • E get(int index)
 Returns the object stored at the specified index within the invoking collection.
  •  ListIterator listIterator( )
Returns an iterator to the start of the invoking list. 
  • ListIterator listIterator(int index)
Returns an iterator to the invoking list that begins at the specified index.
  
The order in which the elements are added to the List is stored, so you can access the elements in the same order. You can do so using either the get(int index) method, or via the Iterator returned by the iterator() method. Here is how:
List listA = new ArrayList();

listA.add("element 0");
listA.add("element 1");
listA.add("element 2");

//access via index
String element0 = listA.get(0);
String element1 = listA.get(1);
String element3 = listA.get(2);


//access via Iterator
Iterator iterator = listA.iterator();
while(iterator.hasNext(){
  String element = (String) iterator.next();
}


//access via new for-loop
for(E object : listA) {
    String element = (String) object;
}
When iterating the list via its Iterator or via the for-loop (which also uses the 
Iterator behind the scene), the elements are iterated in the same sequence they 
are stored in the list. 
 

How to delete elements?

These functions are used to remove elements:
  • remove(E element) 
remove(E element) removes that element in the list, if it is present. All subsequent elements in the list are then moved up in the list. Their index thus decreases by 1. 
  • remove(int index)
remove(int index) removes the element at the given index. All subsequent elements in the list are then moved up in the list. Their index thus decreases by 1. 

How to delete elements?

The list elements can be changed by the function E set(int index, E element) which replaces the element at the specified position in this list with the specified element

[Read more]

JAVA program to handle same function with different number of parameters

Posted On // Leave a Comment
In this post i would like show you a cool feature of java to handle functions with different parameter sets. For example if you want to find sum of a set of parameters which maybe 2or 3or400 you can use this feature instead of doing messy convertions to array.

public class threeDots{

    static void sumIt(int...x){
        int t=0;
        for(int i:x)
            t+=i;
        System.out.println(t);
    }

    public static void main(String[] args) {
        sumIt(1);
        sumIt(1,2);
        sumIt(1,2,3);
        sumIt(1,2,3,4);
        sumIt(1,2,3,4,5);
        sumIt(1,2,3,4,5,6);       
    }
}

Output:
1
3
6
10
15
21
[Read more]

JAVA program to implement Eller's algorithm to generate random maze

Posted On // Leave a Comment

Algorithm:

    Eller's algorithm creates 'perfect' mazes, having only a single path between any two cells, one row at a time. The algorithm itself is incredibly fast, and far more memory efficient than other popular algorithms (such as Prim's and Kruskal's) requiring storage proportional to only a single row. This makes it possible to create mazes of indefinite length on systems with limited memory.

The algorithm is explained below:
  1. Create the first row. No cells will be members of any set

  2. Join any cells not members of a set to their own unique set

  3. Create right-walls, moving from left to right:
    1. Randomly decide to add a wall or not
      • If the current cell and the cell to the right are members of the same set, always create a wall between them. (This prevents loops)
      • If you decide not to add a wall, union the sets to which the current cell and the cell to the right are members.

  4. Create bottom-walls, moving from left to right:
    1. Randomly decide to add a wall or not. Make sure that each set has at least one cell without a bottom-wall (This prevents isolations)
      • If a cell is the only member of its set, do not create a bottom-wall
      • If a cell is the only member of its set without a bottom-wall, do not create a bottom-wall

  5. Decide to keep adding rows, or stop and complete the maze
    1. If you decide to add another row:
      1. Output the current row
      2. Remove all right walls
      3. Remove cells with a bottom-wall from their set
      4. Remove all bottom walls
      5. Continue from Step 2

    2. If you decide to complete the maze
      1. Add a bottom wall to every cell
      2. Moving from left to right:
        • If the current cell and the cell to the right are members of a different set:
          1. Remove the right wall
          2. Union the sets to which the current cell and cell to the right are members.
          3. Output the final row

CODE:

// a utility class to represent single cell
import java.util.*;

public class Cel{
 public boolean right,down;
 
 public List<Cel> set;
 
 public int x,y;
 
 Cel(int a,int b){
  
  x=a;
  
  y=b;
  
  right=false;
  
  down=true;
  
  set=null;
  
 }
 
}
// class to implement the algorithm
import java.util.*;



public class maze{
 
 static Random randomizer = new Random();
 
 static int size;
 
 static int[][] maze;
 
 static Scanner in = new Scanner(System.in);
 
 
 
 /*  Step 2: Grouping ungrouped cells to form new sets    */
 
 static Cel[] makeSet(Cel[] row) {
  
  for(int index = 0; index < row.length; ) {
   
   Cel cell = row[index++];
   
   if(cell.set == null) {
    
    List<Cel> list = new ArrayList<Cel>();
    
    list.add(cell);
    
    cell.set=list;
    
   }
   
  }
  
  return row;
  
 }
 
 /*********************************************************/
 
 
 
 /*  Step 3: Creating right walls                         */
 
 static Cel[] makeRightWalls(Cel[] row) {
  
  for(int i = 1; i < row.length; i++) {
   
   if(isContainsInList(row[i-1].set,row[i])) {
    
    row[i-1].right=true;
    
    continue;
    
   }
   
   if(randomizer.nextBoolean())
   
   row[i-1].right=true;
   
   else
    
   row=merge(row,i);
   
  }
  
  return row;
  
 }
 
 
 
 static Cel[] merge(Cel[] row,int i) {  //utility function
  
  List<Cel> currentList = row[i-1].set;
  
  List<Cel> nextList = row[i].set;
  
  for(Cel j : nextList) {
   
   currentList.add(j);
   
   j.set=currentList;
   
  }
  
  return row;
  
 }
 
 
 
 static boolean isContainsInList(List<Cel> set,Cel cell) {  //utility function
  
  for(Cel i : set) {
   
   if(i==cell)
   
   return true;
   
  }
  
  return false;
  
 }
 
 /*********************************************************/
 
 
 
 /*  Step 4: Creating down walls                          */
 
 static boolean isNotDone(List<Cel> set){    //utility function
  
  boolean rslt=true;
  
  for(Cel x:set)
  
  rslt=rslt&&x.down;
  
  return rslt;
  
 }
 
 
 
 static Cel[] makeDown(Cel[] row){
  
  for(int i=0;i<row.length;i++){
   
   for(Cel x:row[i].set)x.down=true;
   
   while(isNotDone(row[i].set)){
    
    do{
     
     row[i].set.get(randomizer.nextInt(row[i].set.size())).down=false;
     
    }while(randomizer.nextBoolean() || );
    
   }
   
  }
  
  return row;
  
 }
 
 /*********************************************************/
 
 
 
 /*  Driver function to execute the algorithm             */
 
 static public void driver(){
  
  System.out.print("Enter size: ");
  
  size=in.nextInt();
  
  maze=new int[2*size+1][2*size+1];
  
  Cel[] cur=new Cel[size];
  
  for(int i=0;i<size;i++)
  
  cur[i]=new Cel(0,i);
  
  for(int i=2;i<=2*size;i++)
  
  for(int j=2;j<=2*size;j++)
  
  maze[i][j]=0;
  
  for(int i=0;i<size;i++){
   
   cur=makeSet(cur);
   
   cur=makeRightWalls(cur);
   
   cur=makeDown(cur);
   
   if(i==size-1)
   
   cur=end(cur);
   
   printMaze(cur,i);
   
   if(i!=size-1)
   
   cur=genNextRow(cur);
   
  }
  
  //Creating upper and left boundary
  
  for(int i=0;i<=2*size;i++)
  
  maze[i][0]=maze[0][i]=maze[i][2*size]=maze[2*size][i]=1;
  
  for(int i=2;i<=2*size;i+=2)
  
  for(int j=2;j<=2*size;j+=2)
  
  maze[i][j]=1;
  
  for(int i=0;i<2*size+1;i++){
   
   System.out.println();
   
   for(int j=0;j<2*size+1;j++)
   
   System.out.print(maze[i][j]+" ");
   
  }
  
 }
 
 static Cel[] end(Cel[] row) {
  
  for(int i = 1; i < row.length; i++) {
   
   if(findPos(row[i-1].set,row[i]) == -1) {
    
    row[i-1].right=false;
    
    row=merge(row,i);
    
   }
   
  }
  
  return row;
  
 }
 
 
 
 static int findPos(List<Cel> set,Cel x){
  
  Cel[] tmpArray = new Cel[set.size()];
  
  tmpArray = set.toArray(tmpArray);
  
  for(int i=0;i<tmpArray.length;i++)
  
  if(tmpArray[i]==x)
  
  return i;
  
  return -1;
  
 }
 
 
 
 static Cel[] genNextRow(Cel[] pre){
  
  for(int i = 0; i < pre.length;i++ ) {
   
   pre[i].right=false;
   
   pre[i].x++;
   
   if(pre[i].down) {
    
    pre[i].set.remove(findPos(pre[i].set, pre[i]));
    
    pre[i].set=null;
    
    pre[i].down=false;
    
   }
   
  }
  
  return pre;
  
 }
 
 
 
 static void printMaze(Cel[] row,int rowPos){
  
  rowPos=2*rowPos+1;
  
  for(int i=0;i<row.length;i++){
   
   if(row[i].right)
   
   maze[rowPos][2*i+2]=1;
   
   if(row[i].down)
   
   maze[rowPos+1][2*i+1]=1;
   
  }
  
 }
 
 
 
}

// driver class to execute the algorithm
public class runMe{
 
 public static void main(String[] args) {
  
  maze t =new maze();
  
  maze.driver();
  
 }
 
}

SOURCE:  

[Read more]

JAVA program to help jerry find cheese

Posted On // Leave a Comment

ALGORITHM:

Jerry is hungry and needs cheese. Bur cheese is in a maze and jerry needs help to find the cheese.
The maze solving is a classic algorithm under backtracking and ai.The problem is to find a path for the rat to food in a maze.
The problem can be solved trying out different paths possible and find the right path,
This logic can be implemented by a simple recursive algorithm. Since the jerryis performed in stack the processes are done in LIFO manner so if we have to print instructions to jerry we will do the process as cheese finds jerry.
  1. Start with the target
  2. If the cell is not legal (if it is out of maze or the cell is a wall) return false
  3. If starting point has reached return true 
  4. else make the cell a wall(to avoid coming back to the same path from any other instant) and
  5. Take all the cells in  four direction and check whether the path can be reached through any of these cells and print opposite movement if the cell is a part of the path (eg if upper cell is part of path print DOWN)and return true and if not path backtrack and return false.These cells should chosen according to the distance to starting point from the current point.
  

The above maze is:
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
1 0 0 1 0
1 1 1 1 0
So the jerry should move down four times and right three times and up two times and right and then up two times.

CODE:

import java.util.Scanner;

public class Maze{
   
   
    static Scanner in = new Scanner(System.in);
    static int[][] maze;

    static boolean solveMaze(int x,int y,int tx,int ty,int b,int h){

        if(x>=0 && x<b && y>=0 && y<h && maze[x][y]==1){//Checking if current cell is legal
            maze[x][y]-=1;
            if(x==tx && y==ty)//checking if point has reached
                return true;
            boolean up,down,left,right;
            /*
             Calculating horizontal and vertical distances and moving according to it
            */
            int xDiff=tx-x;
            if(xDiff<0)
                xDiff*=-1;
            int yDiff=ty-y;
            if(yDiff<0)
                yDiff*=-1;
            if(xDiff<yDiff){
                if(tx<x){
                    up=solveMaze(x-1,y,tx,ty,b,h);
                    down=solveMaze(x+1,y,tx,ty,b,h);
                }
                else{
                    down=solveMaze(x+1,y,tx,ty,b,h);
                    up=solveMaze(x-1,y,tx,ty,b,h);
                }
                if(ty<y){
                    left=solveMaze(x,y-1,tx,ty,b,h);
                    right=solveMaze(x,y+1,tx,ty,b,h);
                }
                else{
                    right=solveMaze(x,y+1,tx,ty,b,h);
                    left=solveMaze(x,y-1,tx,ty,b,h);
                }
            }
            else{
                if(ty<y){
                    left=solveMaze(x,y-1,tx,ty,b,h);
                    right=solveMaze(x,y+1,tx,ty,b,h);
                }
                else{
                    right=solveMaze(x,y+1,tx,ty,b,h);
                    left=solveMaze(x,y-1,tx,ty,b,h);
                }
                if(tx<x){
                    up=solveMaze(x-1,y,tx,ty,b,h);
                    down=solveMaze(x+1,y,tx,ty,b,h);
                }
                else{
                    down=solveMaze(x+1,y,tx,ty,b,h);
                    up=solveMaze(x-1,y,tx,ty,b,h);
                }
            }
            //print opposite movement if the cell is a part of the path
            if(up||down||left||right){
                if(up)
                    System.out.println("DOWN");
                if(down)
                    System.out.println("UP");
                if(left)
                    System.out.println("RIGHT");
                if(right)
                    System.out.println("LEFT");
                return true;
            }
            maze[x][y]+=1;//backtrack
            return false;
        }
        return false;
    }
    public static void main(String[] args) {
        System.out.println("enter number of rows and columns ");
        System.out.print("Rows: ");
        int b = in.nextInt();
        System.out.print("Columns: ");
        int h = in.nextInt();
        maze=new int[b][h];
        System.out.println("enter maze 1 for path and 0 for wall");
        for(int i=0;i<b;i++)
            for(int j=0;j<h;j++)
                maze[i][j]=in.nextInt();
        System.out.print("Enter Jerry position\nX: ");
        int begx=in.nextInt();
        System.out.print("Y: ");
        int begy=in.nextInt();
        System.out.print("Enter cheese position\nX: ");
        int tarx=in.nextInt();
        System.out.print("Y: ");
        int tary=in.nextInt();
        if(!solveMaze(tarx,tary,begx,begy,b,h))
        System.out.println("no path");
    }
}

OUTPUT:

enter number of rows and columns
Rows: 5
Columns: 5
enter maze 1 for path and 0 for wall
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
1 0 0 1 0
1 1 1 1 0
Enter Jerry position
X: 0
Y: 0
Enter cheese position
X: 0
Y: 4

DOWN
DOWN
DOWN
DOWN
RIGHT
RIGHT
RIGHT
UP
UP
RIGHT
UP
UP
[Read more]

JAVA program to print all permutations of a string

Posted On // Leave a Comment

ALGORITHM:

The permutation of a string is the rearrangement of the string in different orders to form different strings of the same length. A string of length n can have n! permutations.
Source: Mathworld
We will start with each letter of the string and then we found all the possible combinations for the string beginning with that letter. And once we picked a letter in the 2nd position, we then found all the possible combinations that begin with that 2 letter sequence before we changed any of the letters in the first 2 positions. So, basically what we did was choose a letter and then peformed the permutation process starting at the next position to the right before we come back and change the character on the left. 

CODE:

import java.util.Scanner;

public class permutations{
   
    static char[] swap(char[] a,int i,int j){
        char tmp =a[i];
        a[i]=a[j];
        a[j]=tmp;
        return a;
    }
   
    static void printArray(char[] a){
        for (int i=0;i<a.length;i++)
            System.out.print(a[i]);
        System.out.println();
    }

    static void permute(char[] a,int index){
        if(index==a.length){
            printArray(a);
            return;
        }
        for(int i=index;i<a.length;i++){
            a=swap(a,i,index);
            permute(a,index+1);
            a=swap(a,i,index);
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the string: ");
        permute(in.next().toCharArray(),0);
    }
}

OUTPUT:

Enter the string: abc
abc
acb
bac
bca
cba
cab


[Read more]

JAVA program to print all combinations(NOT PERMUTATIONS) of a string

Posted On // Leave a Comment

ALGORITHM:

The problem is to find all combination of letters in a string ,the question should not be mistaken with permutation of string.To find all combinations of a string we follow a simple method: take each element and and group it with rest of the elements and do the same for thus formed new groups.

A diagramatic representation for the string ABC is:

So this logic can be implemented using a recursive algorithm :
  •  Take each group(each elements in beginning) and form new groups for each group by combining it with the rest of elements and repeat this procedure for each newly formed groups until the group size becomes equal to the string size.


CODE:

import java.util.Scanner;

public class comb{

    static void printArray(char[] a,int len){
        for (int i=0;i<=len;i++)
            System.out.print(a[i]);
        System.out.println();
    }

    static void printCombination(char[] a,char[] b,int aBeg,int bEnd){
        for(int i=aBeg;i<a.length;i++){
            b[bEnd+1]=a[i];
            printArray(b,bEnd+1);
            if(i<a.length-1)
                printCombination(a,b,i+1,bEnd+1);
        }
    }

    public static void main(String[] args) {
        System.out.print("Enter string: ");
        char[] a;
        Scanner in = new Scanner(System.in);
        a=in.next().toCharArray();
        char[] b = new char[a.length];
        printCombination(a,b,0,-1);
    }
}

OUTPUT:

Enter string: abc
a
ab
abc
ac
b
bc
c


[Read more]

JAVA program to find all numbers whose sum of digits is equal to an input number

Posted On // Leave a Comment

ALGORITHM:

The problem is to input a number and find all numbers whose digits sum is equal to the input number.
i.e. if the input number is 5 then program should print numbers 5 14 23 32 41.
The problem can be solved by doing a recursive algorithm given below:
  1. Start with first digit 1 to 9
  2. Check whether the number digit's sum has exceeded the target or has reached the target; if it has reached target then print the number; if so return from the function.
  3. If the digit's sum is less than target then try adding digits 1 to 9 to the LSB of the number and recurse the function(from step 2) for each such made new numbers.
The program of algorithm is given below since java has a stack limit of about 1k bytes the program won't work for large numbers :P.

CODE:

import java.util.Scanner;

public class digitSum{

    static boolean isInArray(int[] a,int ele){
        for(int i=0;i<a.length;i++)
            if(a[i]==ele)
                return false;
        return true;
    }

    static int findSum(int[] ar,int end){
        int sum=0;
        for(int i=0;i<=end;i++)
            sum+=ar[i];
        return sum;
    }

    static void printNum(int[] ar,int index,int num){
       
        int sum = findSum(ar,index);
        int diff = num-sum;
        if(diff<0)
            return;
        if(diff==0){
            for (int i=0;i<=index;i++)
                System.out.print(ar[i]);
            System.out.println();  
            return;
        }
        for(int i=1;i<10;i++){
            if(isInArray(ar,i)){
                ar[index+1]=i;
                printNum(ar,index+1,num);
            }
        }
       
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("\nEnter the number: ");
        int num=in.nextInt();
        int[] ar = new int[9];
        for (int i=1;i<=9;i++ ) {
            ar[0]=i;
            printNum(ar,0,num);
        }
    }
}

OUTPUT:

Enter the number: 8
125
134
143
152
17
215
251
26
314
341
35
413
431
512
521
53
62
71
8
[Read more]

JAVA program to perform iterative preorder traversal

Posted On // Leave a Comment

CODE:

import java.util.Scanner;
import java.util.Stack;

public class iterPre{

    static Scanner in = new Scanner(System.in);

        static node inputTree(){
        node temp=new node();
        System.out.print("Enter the value: ");
        temp.data=in.nextInt();
        System.out.print("Enter y if the node "+temp.data+" has left subtree: ");
        if(in.next().charAt(0)=='y')
            temp.left=inputTree();
        else
            temp.left=null;
        System.out.print("Enter y if the node "+temp.data+" has right subtree: ");
        if(in.next().charAt(0)=='y')
            temp.right=inputTree();
        else
            temp.right=null;
        return temp;
    }

    static void iterPreorder(node root){
        if(root == null)
            return;
        node tmp = new node();
        Stack<node> s = new Stack<node>();
        s.push(root);
        while (s.isEmpty()==false) {
            tmp = s.pop();
            System.out.print("\t"+tmp.data);
            if(tmp.right != null)
                s.push(tmp.right);
            if(tmp.left != null)
                s.push(tmp.left);
        }
    }

    public static void main(String[] args) {
        node root = new node();
        root = inputTree();
        iterPreorder(root);
    }

}
[Read more]

JAVA program to traverse inorder without recursion

Posted On // Leave a Comment

CODE:


import java.util.Scanner;
import java.util.Stack;

public class inorderStack{

    static Scanner in = new Scanner(System.in);

    static node inputTree(){
        node temp=new node();
        System.out.print("Enter the value: ");
        temp.data=in.nextInt();
        System.out.print("Enter y if the node "+temp.data+" has left subtree: ");
        if(in.next().charAt(0)=='y')
            temp.left=inputTree();
        else
            temp.left=null;
        System.out.print("Enter y if the node "+temp.data+" has right subtree: ");
        if(in.next().charAt(0)=='y')
            temp.right=inputTree();
        else
            temp.right=null;
        return temp;
    }

    static void inorder(node tree){
        if(tree == null)
            return;
        Stack<node> s = new Stack<node>();
        while((s.isEmpty() == false)||(tree != null)){
            if(tree!=null){
                s.push(tree);
                tree = tree.left;
            }
            else{
                tree = s.pop();
                System.out.print(tree.data+"\t");
                tree = tree.right;
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("Enter the tree: ");
        node tree = new node();
        tree = inputTree();
        System.out.println("Inorder traversal ");
        inorder(tree);   
    }

}
[Read more]

JAVA program to find sibling of parent of a given node

Posted On // Leave a Comment

CODE:

import java.util.Scanner;

public class parentSibling{

    static Scanner in = new Scanner(System.in);

    static node inputTree(){
        node temp=new node();
        System.out.print("Enter the value: ");
        temp.data=in.nextInt();
        System.out.print("Enter y if the node "+temp.data+" has left subtree: ");
        if(in.next().charAt(0)=='y')
            temp.left=inputTree();
        else
            temp.left=null;
        System.out.print("Enter y if the node "+temp.data+" has right subtree: ");
        if(in.next().charAt(0)=='y')
            temp.right=inputTree();
        else
            temp.right=null;
        return temp;
    }

    static void inorder(node tree){
        if(tree==null)
            return;
        inorder(tree.left);
        System.out.print(tree.data+"\t");
        inorder(tree.right);
    }

    static void printSibling(node tree,node par,node parofpar,int X){
        if(tree == null)
            return;
        if(tree.data==X){
            if((par != null)&&(parofpar != null)&&(parofpar.left != null)&&(parofpar.right != null)){
                if(parofpar.left == par)
                    System.out.println("Sibling "+parofpar.right.data);
                if(parofpar.right == par)
                    System.out.println("Sibling "+parofpar.left.data);
            }
            else
                System.out.println("No Sibling");
            return;
        }
        printSibling(tree.left,tree,par,X);
        printSibling(tree.right,tree,par,X);
    }

    public static void main(String[] args) {
        System.out.println("Enter the tree: ");
        node tree = new node();
        tree = inputTree();
        System.out.println("Inorder traversal ");
        inorder(tree);
        System.out.print("\nEnter node: ");
        printSibling(tree,null,null,in.nextInt());
    }

}

[Read more]