Advertisement
zoltanvi

integer Binary Tree implementation (only add)

Jul 15th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1.  
  2. public class Main{
  3.  
  4.     public static void main(String[] args) {
  5.         BinaryTree bt = new BinaryTree();
  6.         bt.add(4);
  7.         bt.add(1);
  8.         bt.add(5);
  9.         bt.add(3);
  10.         bt.add(3);
  11.     }
  12.  
  13. }
  14.  
  15. class BinaryTree{
  16.  
  17.     private class Node{
  18.         int data;
  19.         Node left;
  20.         Node right;
  21.  
  22.         public Node(int data){
  23.             this.data = data;
  24.             left = null;
  25.             right = null;
  26.         }
  27.     }
  28.  
  29.     Node root;
  30.     int size;
  31.  
  32.     public BinaryTree(){
  33.         root = null;
  34.         size = 0;
  35.     }
  36.  
  37.     public BinaryTree(int data){
  38.         root = new Node(data);
  39.         size = 1;
  40.     }
  41.  
  42.     public void add(int data){
  43.         if(size == 0){
  44.             root = new Node(data);
  45.             size++;
  46.         } else {
  47.             Node current = root;
  48.             boolean found = false;
  49.             while(!found){
  50.                 if(current.data >= data){
  51.                     if(current.left != null){
  52.                         current = current.left;
  53.                     } else {
  54.                         found = true;
  55.                     }
  56.                 } else if(current.data < data){
  57.                     if(current.right != null){
  58.                         current = current.right;
  59.                     } else{
  60.                         found = true;
  61.                     }
  62.                 }
  63.             }
  64.  
  65.             if(current.data >= data){
  66.                 current.left = new Node(data);
  67.             } else {
  68.                 current.right = new Node(data);
  69.             }
  70.             size++;
  71.         }
  72.     }
  73.    
  74.  
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement