From f62311428f96b3da6da43d8803215784b35b0d9d Mon Sep 17 00:00:00 2001 From: Adam Blank <blank@caltech.edu> Date: Thu, 7 Feb 2019 00:47:09 -0800 Subject: [PATCH] Update BSTDictionary.java --- .../cs2/datastructures/BSTDictionary.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/edu/caltech/cs2/datastructures/BSTDictionary.java b/src/edu/caltech/cs2/datastructures/BSTDictionary.java index 4924a60..d62b5cc 100644 --- a/src/edu/caltech/cs2/datastructures/BSTDictionary.java +++ b/src/edu/caltech/cs2/datastructures/BSTDictionary.java @@ -56,6 +56,32 @@ public class BSTDictionary<K extends Comparable<K>, V> implements IDictionary<K, public Iterator<K> iterator() { return null; } + + @Override + public String toString() { + if (this.root == null) { + return "{}"; + } + + StringBuilder contents = new StringBuilder(); + + IQueue<BSTNode<K, V>> nodes = new ArrayDeque<>(); + BSTNode<K, V> current = this.root; + while (current != null) { + contents.append(current.key + ": " + current.value + ", "); + + if (current.children[0] != null) { + nodes.enqueue(current.children[0]); + } + if (current.children[1] != null) { + nodes.enqueue(current.children[1]); + } + + current = nodes.dequeue(); + } + + return "{" + contents.toString().substring(0, contents.length() - 2) + "}"; + } protected static class BSTNode<K, V> { public final K key; -- GitLab