class node {
node left, right;
int value;
node(int x){
this.value = x;
}
}
class tree {
node root;
void add(int x){
node curr = new node(x);
if(root == null){
root = curr;
}
else{
check(x, root);
}
}
void check(int x, node root){
if(x < root.value ){
if(root.left == null){
node curr= new node(x);
root.left = curr;
return;
}
check(x, root.left);
}
if(x > root.value ){
if(root.right == null){
node curr= new node(x);
root.right = curr;
return;
}
check(x, root.right);
}
}
void printin(){
node temp = root;
inorder(temp);
}
void printpre(){
node temp = root;
preorder(temp);
}
void printpos(){
node temp = root;
postorder(temp);
}
static void inorder(node temp){
if(temp == null){
return;
}
inorder(temp.left );
System.out.print(" " + temp.value);
inorder(temp.right);
}
static void postorder(node temp){
if(temp == null){
return;
}
postorder(temp.left );
postorder(temp.right);
System.out.print(" " + temp.value);
}
static void preorder(node temp){
if(temp == null){
return;
}
System.out.print(" "+ temp.value);
preorder(temp.left);
preorder(temp.right);
}
}
class mywork{
public static void main(String args[]){
tree t1 = new tree();
t1.add(4);
t1.add(2);
t1.add(3);
t1.add(6);
t1.add(1);
t1.add(5);
t1.add(7);
t1.printpos();
System.out.println();
t1.printpre();
System.out.println();
t1.printin();
}
}
Comments
Post a Comment