package Data_structure;
class TNode{
TNode left,right;
int data;
TNode(int value){
data=value;
}
}
public class TreeImplementation {
TNode root;
TreeImplementation(){
}
//insert Elements
public void insert(int tdata){
TNode newNode=new TNode(tdata);
TNode current=root;
if(root==null)root=newNode;
else{
while(true){
if(current.data>tdata){
if(current.left==null){
current.left=newNode;
break;
}
current=current.left;
}
if(current.data<tdata){
if(current.right==null){
current.right=newNode;
break;
}
current=current.right;
}
}
}
}
public void preOrder(TNode tem){
if(tem!=null){
System.out.println(tem.data);
preOrder(tem.left);
preOrder(tem.right);
}
else return;
}
public void inOrder(TNode tem){
if(tem!=null){
inOrder(tem.left);
System.out.println(tem.data);
inOrder(tem.right);
}
else return;
}
public void postOrder(TNode tem){
if(tem!=null){
postOrder(tem.left);
postOrder(tem.right);
System.out.println(tem.data);
}
else return;
}
public static void main(String [] shan){
TreeImplementation bst=new TreeImplementation();
bst.insert(23);
bst.insert(19);
bst.insert(1);
bst.insert(45);
bst.insert(56);
bst.insert(34);
bst.insert(2);
bst.insert(77);
bst.insert(100);
System.out.println("PreOrder");
bst.preOrder(bst.root);
System.out.println("inOrder");
bst.inOrder(bst.root);
System.out.println("postOrder");
bst.postOrder(bst.root);
}
}
Input:
23 19 1 45 56 34 2 77 100
OutPut:
class TNode{
TNode left,right;
int data;
TNode(int value){
data=value;
}
}
public class TreeImplementation {
TNode root;
TreeImplementation(){
}
//insert Elements
public void insert(int tdata){
TNode newNode=new TNode(tdata);
TNode current=root;
if(root==null)root=newNode;
else{
while(true){
if(current.data>tdata){
if(current.left==null){
current.left=newNode;
break;
}
current=current.left;
}
if(current.data<tdata){
if(current.right==null){
current.right=newNode;
break;
}
current=current.right;
}
}
}
}
public void preOrder(TNode tem){
if(tem!=null){
System.out.println(tem.data);
preOrder(tem.left);
preOrder(tem.right);
}
else return;
}
public void inOrder(TNode tem){
if(tem!=null){
inOrder(tem.left);
System.out.println(tem.data);
inOrder(tem.right);
}
else return;
}
public void postOrder(TNode tem){
if(tem!=null){
postOrder(tem.left);
postOrder(tem.right);
System.out.println(tem.data);
}
else return;
}
public static void main(String [] shan){
TreeImplementation bst=new TreeImplementation();
bst.insert(23);
bst.insert(19);
bst.insert(1);
bst.insert(45);
bst.insert(56);
bst.insert(34);
bst.insert(2);
bst.insert(77);
bst.insert(100);
System.out.println("PreOrder");
bst.preOrder(bst.root);
System.out.println("inOrder");
bst.inOrder(bst.root);
System.out.println("postOrder");
bst.postOrder(bst.root);
}
}
Input:
23 19 1 45 56 34 2 77 100
OutPut:
No comments:
Post a Comment