import java.util.*; class TreeNode { KeyValuePair kvp; // A tree node now stores the Key-Value pair as an object. TreeNode left; // The usual pointers. TreeNode right; } public class BinaryTreeMap3 { TreeNode root = null; int numItems = 0; KeyValuePair[] allPairs; // We will place the elements in this array. int currentIndex = 0; public void add (KeyValuePair kvp) { // If empty, create new root. if (root == null) { root = new TreeNode (); root.kvp = kvp; numItems ++; return; } // Search to see if it's already there. if ( contains (kvp.key) ) { // Handle duplicates. return; } // If this is a new piece of data, insert into tree. recursiveInsert (root, kvp); numItems ++; } void recursiveInsert (TreeNode node, KeyValuePair kvp) { // Compare input data with data in current node. if ( kvp.key.compareTo (node.kvp.key) < 0 ) { // It's less. Go left if possible, otherwise we've found the correct place to insert. if (node.left != null) { recursiveInsert (node.left, kvp); } else { node.left = new TreeNode (); node.left.kvp = kvp; } } // Otherwise, go right. else { // It's greater. Go right if possible, otherwise we've found the correct place to insert. if (node.right != null) { recursiveInsert (node.right, kvp); } else { node.right = new TreeNode (); node.right.kvp = kvp; } } } public int size () { return numItems; } public boolean contains (String key) { if (numItems == 0) { return false; } TreeNode node = recursiveSearch (root, key); if (node == null) { return false; } return true; } public KeyValuePair getKeyValuePair (String key) { if (numItems == 0) { return null; } TreeNode node = recursiveSearch (root, key); if (node == null) { return null; } return node.kvp; } TreeNode recursiveSearch (TreeNode node, String key) { // If input string is at current node, it's in the tree. if ( key.compareTo (node.kvp.key) == 0 ) { // Found. return node; } // Otherwise, navigate further. if ( key.compareTo (node.kvp.key) < 0 ) { // Go left if possible, otherwise it's not in the tree. if (node.left == null) { return null; } else { return recursiveSearch (node.left, key); } } else { // Go right if possible, otherwise it's not in the tree. if (node.right == null) { return null; } else { return recursiveSearch (node.right, key); } } } public KeyValuePair[] getAllKeyValuePairs () { if (root == null) { System.out.println ("ERROR: getAll(): null root"); return null; } allPairs = new KeyValuePair [numItems]; inOrderTraversal (root); return allPairs; } void inOrderTraversal (TreeNode node) { if (node.left != null) { inOrderTraversal (node.left); } allPairs[currentIndex] = node.kvp; currentIndex ++; if (node.right != null) { inOrderTraversal (node.right); } } }