|
| 1 | +package tree.ternarysearch; |
| 2 | + |
| 3 | +public class TST { |
| 4 | + private Node root; |
| 5 | + |
| 6 | + public void put(String key, int value) { |
| 7 | + root = put(root, key, value, 0); |
| 8 | + } |
| 9 | + |
| 10 | + public Integer get(String key) { |
| 11 | + Node node = get(root, key, 0); |
| 12 | + |
| 13 | + if (node == null) { |
| 14 | + return null; |
| 15 | + } |
| 16 | + |
| 17 | + return node.getValue(); |
| 18 | + } |
| 19 | + |
| 20 | + private Node put(Node node, String key, int value, int index) { |
| 21 | + char c = key.charAt(index); |
| 22 | + |
| 23 | + if (node == null) { |
| 24 | + node = new Node(c); |
| 25 | + } |
| 26 | + if (c < node.getCharacter()) { |
| 27 | + node.setLeft(put(node.getLeft(), key, value, index)); |
| 28 | + } else if (c > node.getCharacter()) { |
| 29 | + node.setRight(put(node.getRight(), key, value, index)); |
| 30 | + } else if (index < key.length() - 1){ |
| 31 | + node.setMiddle(put(node.getMiddle(), key, value, index + 1)); |
| 32 | + } else { |
| 33 | + node.setValue(value); |
| 34 | + } |
| 35 | + |
| 36 | + return node; |
| 37 | + } |
| 38 | + |
| 39 | + // running time complexity is sub-linear in case of search misses |
| 40 | + private Node get(Node node, String key, int index) { |
| 41 | + if (node == null) { |
| 42 | + return null; |
| 43 | + } |
| 44 | + |
| 45 | + char c = key.charAt(index); |
| 46 | + |
| 47 | + if (c < node.getCharacter()) { |
| 48 | + return get(node.getLeft(), key, index); |
| 49 | + } else if (c > node.getCharacter()) { |
| 50 | + return get(node.getRight(), key, index); |
| 51 | + } else if (index < key.length() - 1) { |
| 52 | + return get(node.getMiddle(), key, index + 1); |
| 53 | + } else { |
| 54 | + return node; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | +} |
0 commit comments