-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTST.java
More file actions
61 lines (43 loc) · 1.2 KB
/
TST.java
File metadata and controls
61 lines (43 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package TST;
public class TST {
private Node rootNode;
public void put(String key, int value){
rootNode = put(rootNode,key,value,0);
}
private Node put(Node node, String key, int value, int index) {
char c = key.charAt(index);
if( node == null ){
node = new Node(c);
}
if( c < node.getCharacter() ){
node.setLeftNode(put(node.getLeftNode(),key,value,index));
}else if( c > node.getCharacter() ){
node.setRightNode(put(node.getRightNode(),key,value,index));
}else if( index < key.length()-1 ){
node.setMiddleNode(put(node.getMiddleNode(),key,value,index+1));
}else{
node.setValue(value);
}
return node;
}
public Integer get(String key){
Node node = get(rootNode,key,0);
if( node == null ){
return null;
}
return node.getValue();
}
private Node get(Node node, String key, int index) {
if( node == null ) return null;
char c = key.charAt(index);
if( c < node.getCharacter() ){
return get(node.getLeftNode(),key,index);
}else if( c > node.getCharacter() ){
return get(node.getRightNode(), key, index);
}else if( index < key.length()-1){
return get(node.getMiddleNode(),key,index+1);
}else{
return node;
}
}
}