LapisSea

Untitled

Apr 27th, 2017
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.92 KB | None | 0 0
  1. public class IntTree<T>{
  2.    
  3.     private class Node{
  4.        
  5.         int     key;
  6.         T       value;
  7.         Node    less,more;
  8.        
  9.         public Node(int key, T value){
  10.             this.key=key;
  11.             this.value=value;
  12.         }
  13.        
  14.         public T get(int key){
  15.             if(this.key==key) return value;
  16.            
  17.             Node child=key>this.key?more:less;
  18.             if(child==null) return null;
  19.            
  20.             return child.get(key);
  21.         }
  22.        
  23.         public void set(int key, T value){
  24.             if(this.key==key) this.value=value;
  25.             else if(key>this.key){
  26.                 if(more==null) more=new Node(key, value);
  27.                 else more.set(key, value);
  28.             }
  29.             else{
  30.                 if(less==null) less=new Node(key, value);
  31.                 else less.set(key, value);
  32.             }
  33.            
  34.         }
  35.        
  36.     }
  37.    
  38.     private Node root;
  39.    
  40.     public void set(int key, T value){
  41.         if(root==null) root=new Node(key, value);
  42.         else root.set(key, value);
  43.     }
  44.    
  45.     public T get(int key){
  46.         if(root==null) return null;
  47.         return root.get(key);
  48.     }
  49.    
  50.     public void clear(){
  51.         root=null;
  52.     }
  53. }
Add Comment
Please, Sign In to add comment