import java.util.*;
class node {
int value;
node right, left;
node(int x) {
this.value = x;
}
}
class tree {
Queue<node> col = new LinkedList<>();
node root;
void add(int x) {
if (root == null) {
node temp = new node(x);
root = temp;
return;
}
find_position(root, x);
}
void find_position(node temp, int x) {
if (temp == null) {
node obj = new node(x);
temp = obj;
return;
}
if (x < temp.value) {
if (temp.left == null) {
node obj = new node(x);
temp.left = obj;
} else {
find_position(temp.left, x);
}
}
if (x > temp.value) {
if (temp.right == null) {
node obj = new node(x);
temp.right = obj;
} else {
find_position(temp.right, x);
}
}
}
void printin() {
node temp = root;
inorder(temp);
}
void inorder(node temp) {
if (temp == null) {
return;
}
if (temp.left == null && temp.right == null) {
System.out.print(" " + temp.value);
return;
}
if (temp.left != null) {
inorder(temp.left);
}
System.out.print(" " + temp.value);
if (temp.right != null) {
inorder(temp.right);
}
}
void print() {
node temp = root;
while (temp != null) {
System.out.print(" " + temp.value);
if (temp.left != null) {
col.add(temp.left);
}
if (temp.right != null) {
col.add(temp.right);
}
temp = col.poll();
}
}
}
class mywork {
public static void main(String []args) {
tree t1 = new tree();
t1.add(5);
t1.add(1);
t1.add(3);
t1.add(6);
t1.add(4);
t1.add(7);
t1.printin();
System.out.println();
t1.print();
}
}
Comments
Post a Comment