Creating binary tree

Creating binary tree.




class Tree{
BTree root;

class BTree{
BTree left;
BTree right;
int data;
BTree(int data){
this.data = data;
left = null;
right = null;
}
}
void insert(int data) {
root = insrt(root,data);
}

public BTree insrt(BTree root,int data) {
if(root == null) {
root = new BTree(data);
return root;
}
if(data<root.data ) {
root.left = insrt(root.left, data);
}else {
root.right = insrt(root.right, data);
}
return root;
}

public void inOrder(BTree root) {
if(root == null)return;
inOrder(root.left);
System.out.print(root.data+" ");
inOrder(root.right);
}

public void preOrder(BTree root) {
if(root == null)return;
System.out.print(root.data+" ");
preOrder(root.left);
preOrder(root.right);
}

public void postOrder(BTree root) {
if(root == null)return;
postOrder(root.left);
postOrder(root.right);
System.out.print(root.data+" ");
}

public boolean searchN(BTree root, int n){ if(root == null) return false; if(root.data == n) return true; else{ if(n<root.data){ return searchN(root.left, n); }else{ return searchN(root.right, n); } } }

 }

 public class BinaryTree {

public static void main(String[] args) {

Tree t = new Tree();
int[] arr = {50,30,20,40,70,60,80};
for(int i=0;i<arr.length;i++) {
t.insert(arr[i]);
}
t.inOrder(t.root);
System.out.println();
t.preOrder(t.root);
System.out.println();
t.postOrder(t.root);
System.out.println(t.searchN(t.root, 20)); // result : true
System.out.println(t.searchN(t.root, 200)); // result : false

}
 }





Post a Comment

Previous Post Next Post