/*
Tree is a non-linear Data Structure.
root
|
/------------------------------\
left right
| |
/--------------\ /-----------------\
left right left right
\
\
\
leaf
1.Binary Tree.
2.AVL Tree.
3.Red Black Tree.
*/
//Structure of Tree In Java Class which hold the
Data and pointer of left and right node
class node{
int data;
node right;
node left;
node(int data){
this.data=data;
}
}
//Binary Tree Class To Access The node Class
class binaryTree{
node root;
binaryTree(){
root=null;
}
public static void main(String[] args){
binaryTree t=new binaryTree();
t.insert(15);
t.insert(5);
t.insert(10);
t.insert(20);
t.insert(25);
t.traverse(t.root);
}
public void insert(int data){
root=addNode(root,data);
}
public node addNode(node root,int data){
if(root==null){
return new node(data);
}
else if(root.data>data){
root.left=addNode(root.left,data);
}
else if(root.data<data){
root.right=addNode(root.right,data);
}
else{
return root;
}
return root;
}
//Left->Right->Root
//Right->Left->Root
//Root->Left->Right
//Root->Right->Left
public void Traverse(node root){
if(root!=null){
System.out.println(root.data);
traverse(root.left);
traverse(root.right);
}
}
}
Comments
Post a Comment