Skip to content

Instantly share code, notes, and snippets.

@lubaochuan
Created December 6, 2022 21:07
Show Gist options
  • Save lubaochuan/4b9d36434c3b0025111164b29137fe21 to your computer and use it in GitHub Desktop.
Save lubaochuan/4b9d36434c3b0025111164b29137fe21 to your computer and use it in GitHub Desktop.
import java.util.LinkedList;
import java.util.Iterator;
import tree.LinkedBinarySearchTree;
public class MyTreeMap{
LinkedBinarySearchTree<Element> tree =
new LinkedBinarySearchTree<Element>();
public LinkedList<Integer> put(String key, Integer location){
Element element = new Element(key, null);
Element old = tree.find(element);
if (old != null){
LinkedList updated = old.getValue();
updated.add(location);
tree.addElement(new Element(key, updated));
return old.getValue();
}else{
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(location);
tree.addElement(new Element(key, list));
return null;
}
}
public LinkedList<Integer> get(String key){
Element target = new Element(key, null);
Element result = tree.find(target);
if(result != null){
return result.getValue();
}else{
return null;
}
}
/**
* Create an inorder iterator of the Keys in the tree.
* @return inorder iterator of the Keys
*/
public Iterator<String> keys(){
LinkedList<String> keys = new LinkedList<String>();
Iterator<Object> it = tree.inOrderIterator();
while(it.hasNext()){
Element e = (Element)it.next();
keys.add(e.getKey());
}
return keys.iterator();
}
public String toString(){
String result = "";
Iterator<Object> it = tree.inOrderIterator();
while(it.hasNext()){
Element e = (Element)it.next();
result += e+"\n";
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment