Binary Seaarch Tree

1. Node
Node.java


 package com.nrs.ds.tree;  
 public class Node {  
      int value;  
      Node left;  
      Node right;  
      public Node(int value, Node left, Node right){  
           this.value = value;  
           this.left = left;  
           this.right = right;  
      }  
 }  
2.
BinarySearchTreeImpl .java
 package com.nrs.ds.tree;  
 public class BinarySearchTreeImpl {  
      Node root;  
      public BinarySearchTreeImpl(){  
           root = null;  
      }  
      public Node nodeCreate(int value){  
           return new Node(value, null, null);  
      }  
      public void add(Node start, Node newNode){  
           if(root == null){  
                root = newNode;  
                return;  
           }  
           if(newNode.value > start.value){  
                if(start.right == null){  
                     start.right = newNode;  
                }  
                     add(start.right, newNode);  
           }  
           if(newNode.value < start.value){  
                if(start.left == null){  
                     start.left = newNode;  
                }  
                add(start.left, newNode);  
           }  
      }  
      public void search(int value, Node start){  
           if(start == null){  
                System.out.println("Node is not fount");  
           }  
           if(start.value == value){  
                System.out.println("Node is fount");  
                return;  
           }  
           if(value > start.value){  
                search(value, start.right);  
           }  
           if(value < start.value){  
                search(value, start.left);  
           }  
      }  
 }  
3.Test:
 package com.nrs.ds.tree;  
 public class BinarySearchTreeTest {  
      public static void main(String[] args) {  
           BinarySearchTreeImpl bst = new BinarySearchTreeImpl();  
           bst.add(bst.root, bst.nodeCreate(10));  
           bst.add(bst.root, bst.nodeCreate(12));  
           bst.add(bst.root, bst.nodeCreate(11));  
           bst.add(bst.root, bst.nodeCreate(13));  
           bst.add(bst.root, bst.nodeCreate(6));  
           bst.search(11, bst.root);  
      }  
 }  
Output:

Comments

Popular posts from this blog

Tournament Tree or Winner Tree

Linked List

Heaps