BST Switch
BST Switch
import java.util.*;
class BST{
Node root;
class Node{
int data;
Node left;
Node right;
Node(int data){
this.data=data;
this.left=null;
this.right=null;
root=insert_rec(root,data);
if(root==null){
return nn;
if(data<root.data){
root.left=insert_rec(root.left,data);
}
else{
root.right=insert_rec(root.right,data);
return root;
inorder_rec(root);
if (root == null) {
return;
inorder_rec(root.left);
System.out.print(root.data+" ");
inorder_rec(root.right);
preorder_rec(root);
if (root == null) {
return;
System.out.print(root.data+" ");
preorder_rec(root.left);
preorder_rec(root.right);
postorder_rec(root);
if (root == null) {
return;
postorder_rec(root.left);
postorder_rec(root.right);
System.out.print(root.data+" ");
max_rec(root);
min_rec(root);
if(root==null){
return;
while(root.right!=null){
root=root.right;
}
if(root==null){
return;
while(root.left!=null){
root=root.left;
return count_rec(root);
if (root == null) {
return 0;
int leftcount=count_rec(root.left);
int rightcount=count_rec(root.right);
return 1+leftcount+rightcount;
return sum_rec(root);
}
if (root == null) {
return 0;
int left_tree=sum_rec(root.left);
int right_tree=sum_rec(root.right);
return root.data+left_tree+right_tree;
b_search(root,t);
if(root==null){
return;
if (root.data == t) {
System.out.println("Element found");
return;
else if(root.data<t)
b_search(root.right,t);
else
b_search(root.left,t);
}
r_tree_rec(root,t);
if(root==null){
return;
if (root.data == t) {
inorder_rec(root.right);
else if(root.data<t)
r_tree_rec(root.right,t);
else
r_tree_rec(root.left,t);
l_tree_rec(root,t);
if(root==null){
return;
}
if (root.data == t) {
inorder_rec(root.left);
else if(root.data<t)
l_tree_rec(root.right,t);
else
l_tree_rec(root.left,t);
diff_rec(root,t);
if(root==null){
return;
if (root.data == t) {
int leftside=sum_rec(root.left);
int rightside=sum_rec(root.right);
int ans=Math.abs(leftside-rightside);
System.out.println(ans);
else if(root.data<t)
diff_rec(root.right,t);
else
diff_rec(root.left,t);
t.insert(17);t.insert(28);t.insert(53);t.insert(49);t.insert(76);
t.insert(1);t.insert(14);t.insert(15);t.insert(23);t.insert(36);
boolean k=true;
while(k){
int choice=sc.nextInt();
switch(choice){
case 1:
System.out.println("Inorder Traversal");
t.inorder();
break;
case 2:
System.out.println("Preorder Traversal");
t.preorder();
break;
case 3:
System.out.println("Postorder Traversal");
t.postorder();
break;
case 4:
t.max();
t.min();
break;
case 5:
break;
case 6:
break;
case 7:
int target=sc.nextInt();
t.search(target);
break;
case 8:
t.r_tree(28);
break;
case 9:
t.l_tree(53);
break;
case 10:
t.diff(28);
break;
case 11:
k = false;
System.out.println("Exiting");
break;