In this article we will learn about how can we create a binary search tree and insert an element in this tree as well as we will see how can we do the inorder traversal.
class Node
{
int data;
Node left,right;
Node(int data)
{
this.data=data;
}
}
class SimpleBST
{
public static void inorder(Node root)
{
if(root!=null)
{
inorder(root.left);
System.out.print(root.data+" ");
inorder(root.right);
}
}
public static boolean search(Node root,int data)
{
if(root ==null)
return false;
else{
if(data>root.data)
return search(root.right,data);
if(data<root.data)
return search(root.left,data);
if(data==root.data)
return true;
}
return false;
}
public static Node insert(Node root,int data)
{
if(root==null)
{
return new Node(data);
}
else{
if(data>root.data)
root.right=insert(root.right,data);
if(data<root.data)
root.left=insert(root.left,data);
}
return root;
}
public static void main(String args[])
{
Node root=new Node(10);
inorder(root);
root.left=new Node(8);
root.right=new Node(15);
root.left.left=new Node(4);
root.left.right=new Node(9);
root.right.left=new Node(12);
root.right.right=new Node(18);
System.out.println("New tree is");
inorder(root);
System.out.println("\nvalue is present :-");
System.out.println(search(root,55));
root=insert(root,11);
root=insert(root,13);
inorder(root);
}
}