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());
}
}
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());
}
}
0 comments :
Post a Comment