1 29 package jegg.btree; 30 31 34 public class BinaryTree 35 { 36 private Node root; 37 public BinaryTree() 38 { 39 } 41 public void insert(final int pos, final Object obj) 42 { 43 if (null == root) 44 { 45 root = new Node(pos,obj); 46 } 47 else 48 { 49 Node cur = root; 50 while (null != cur) 51 { 52 int cur_pos = cur.getPosition(); 53 if (cur_pos == pos) 54 { 55 cur.setObject(obj); 56 break; 57 } 58 else 59 if (cur_pos > pos) 60 { 61 Node nxt = cur.getLesser(); 62 if (null == nxt) 63 { 64 cur.setLesser(new Node(pos,obj)); 65 break; 66 } 67 cur = nxt; 68 } 69 else 70 if (cur_pos < pos) 71 { 72 Node nxt = cur.getGreater(); 73 if (null == nxt) 74 { 75 cur.setGreater(new Node(pos,obj)); 76 break; 77 } 78 cur = nxt; 79 } 80 } 81 } 82 } 83 public Object get(int pos) 84 { 85 Node cur = root; 86 Object o = null; 87 while (null != cur) 88 { 89 int cur_pos = cur.getPosition(); 90 if (cur_pos == pos) 91 { 92 o = cur.getObject(); 93 break; 94 } 95 else 96 if (cur_pos > pos) 97 { 98 cur = cur.getLesser(); 99 } 100 else 101 if (cur_pos < pos) 102 { 103 cur = cur.getGreater(); 104 } 105 } 106 return o; 107 } 108 public Object getAtLeast(int pos) 109 { 110 Node cur = root; 111 Object o = null; 112 while (null != cur) 113 { 114 int cur_pos = cur.getPosition(); 115 if (cur_pos >= pos) 116 { 117 o = cur.getObject(); 118 break; 119 } 120 else 121 { 122 cur = cur.getGreater(); 123 } 124 } 125 return o; 126 } 127 public Object getAtMost(int pos) 128 { 129 Node cur = root; 130 Object o = null; 131 while (null != cur) 132 { 133 int cur_pos = cur.getPosition(); 134 if (cur_pos <= pos) 135 { 136 o = cur.getObject(); 137 break; 138 } 139 else 140 { 141 cur = cur.getLesser(); 142 } 143 } 144 return o; 145 } 146 } 147 | Popular Tags |