Binary Tree Structure:
class BinaryTree
{
TreeNode root;
public BinaryTree()
{
root=null;
}
public int countNodes()
{
return countNodes(root);
}
private int countNodes(TreeNode r)
{
if(r==null)
return 0;
else
{
int l=1;
l+=countNodes(r.getLeft());
l+=countNodes(r.getRight());
return l;
}
}
public boolean Search(int value)
{
return Search(root,value);
}
public boolean Search(TreeNode r,int val)
{
boolean Found=false;
while(r!=null && !Found)
{
int rval=r.getData();
if(val<rval)
r=r.getLeft();
else if (val>rval)
r=r.getRight();
else
Found =true;
Found=Search(r,val);
}
return Found;
}
public void inorder()
{
inorder (root);
}
private void inorder(TreeNode r)
{
if(r!=null)
{
inorder(r.getLeft());
System.out.println(r.getData() + " ");
inorder(r.getRight());
}
}
public void preorder()
{
preorder (root);
}
private void preorder(TreeNode r)
{
if(r!=null)
{
System.out.println(r.getData() + " ");
preorder (r.getLeft());
preorder (r.getRight());
}
}
public void postorder()
{
postorder(root);
}
private void postorder(TreeNode r)
{
if(r!=null)
{
postorder (r.getLeft());
postorder (r.getRight());
System.out.println(r.getData() + " ");
}
}
public boolean add(int value)
{
if(root==null)
{
root=new TreeNode(value);
return true;
}
else
return root.add(value);
}
}
Main Adapter:
import java.util.*;
class Bst
{
protected static BinaryTree bt;
public static void main()
{
bt=new BinaryTree();
System.out.println("Inorder ");
bt.inorder();
System.out.println("Preorder ");
bt.preorder();
System.out.println("Postorder ");
bt.postorder();
int l=bt.countNodes();
System.out.println("No. of nodes is " + l);
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value to be searched");
if(bt.Search(sc.nextInt())==true)
System.out.println("Found");
else
System.out.println("Not found");
}
}
No comments:
Post a Comment
Convey your thoughts to authors.