This repository was archived by the owner on Dec 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDictionaryTree.java
More file actions
87 lines (78 loc) · 2.59 KB
/
DictionaryTree.java
File metadata and controls
87 lines (78 loc) · 2.59 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/* This class represents a dictionary: a data structure used for storing values associated with a key.
* It stores objects of the class DictionaryPair (which contains two elements, key and value) in a Tree.
* One can search based on the key.
* Personally I would call this class 'Dictionary' but since we already made another implementation of it
* called 'Dictionary', this one is called DictionaryTree. Personally I would get rid of the normal 'Dictionary'
* class and just rename this one. But I believe we are to hand in all the classes used for this class,
* whether or not they are implemented in the final version of our project.
* Author: Seppe Lampe
*/
public class DictionaryTree{
private RedBlackTree data;
public class DictionaryPair implements Comparable
{
private Comparable key;
private Comparable value;
public DictionaryPair (Comparable someKey, Comparable someValue)
{
this.key = someKey;
this.value = someValue;
}
@Override
public int compareTo(Object comp) { //O(1)
return this.getKey().compareTo(((DictionaryPair)comp).getKey());
}
public Comparable getKey() //O(1)
{
return key;
}
public Comparable getValue() //O(1)
{
return value;
}
public void setKey(Comparable newKey) //O(1)
{
key = newKey;
}
public void setValue(Comparable newValue) //O(1)
{
value = newValue;
}
}
public DictionaryTree()
{
data = new RedBlackTree();
}
// Adds a key and value to the Dictionary
public void add(Comparable key,Comparable value) //O(log(n))
{
data.insert(new DictionaryPair(key, value));
}
// Searches for a DictionaryPair based on a certain key, returns the DictionaryPair.
public DictionaryPair find(Comparable key) { //O(log(n))
return (DictionaryPair)data.find(new DictionaryPair(key, 0));
}
// Searches for a DictionaryPair based on a certain key, returns the key of the DictionaryPair.
public Comparable findKey(Comparable key) { //O(log(n))
DictionaryPair pair = this.find(key);
if(pair == null) {
return null;
}
else {
return pair.getKey();
}
}
// Searches for a DictionaryPair based on a certain key, returns the value of the DictionaryPair.
public Comparable findValue(Comparable key) { //O(log(n))
DictionaryPair pair = this.find(key);
if(pair == null) {
return null;
}
else {
return pair.getValue();
}
}
public void traverseInOrder(TreeAction action) { // O(n)
data.traverseNode(data.root, action);
}
}