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 postorder traversal.
class Node
{
int data;
Node left,right;
Node(int data)
{
this.data=data;
}
}
class SimpleBST
{
public static void postorder(Node root)
{
if(root!=null)
{
inorder(root.left);
inorder(root.right);
System.out.print(root.data+" ");
}
}
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);
postorder(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");
postorder(root);
System.out.println("\nvalue is present :-");
System.out.println(search(root,55));
root=insert(root,11);
root=insert(root,13);
postorder(root);
}
}