// Recursive put method public class BST, Value> { /* =========================== Node structure =========================== */ private class Node { private Key key; private Value val; private Node left; private Node right; public Node(Key key, Value val) { this.key = key; this.val = val; } } private Node root; // References the root node of the BST /* ========================================================== put( key, val ): put the (key, val) pair into the BST ========================================================== */ public void put(Key key, Value val) { root = put(root, key, val); // Call a recursive method to do the // work at node "root" // This OVERLOADED put method // insert (key,val) at a given node // as root AND return the BST at that root } /* ========================================================== put(myRoot, key, val ): put the (key, val) pair into a BST at the root node "myRoot" ========================================================== */ public Node put(Node r, Key key, Value val) { Node sol; if ( r == null ) { // Base case 1: empty BST sol = new Node( key, val ); // Sol: make a BST with 1 node return sol; // Return the solution } else if ( key == r.key ) { // Base case 2: key is at the root node r r.val = val; // Replace value in r return r; // Return the same tree ! } /* ------------------------------------------ Recursive cases: NON empty BST ------------------------------------------ */ else if ( key.compareTo( r.key ) < 0 ) { // (key value) goes in left subtree sol = put ( r.left, key, val ); // Tell a helper to insert (key,val) // into the left tree and give you // the solution. r.left = sol; // I can now solve the problem // but attaching the tree as my left // tree return (r); // return the solution. } else { // (key value) MUST go in right subtree sol = put ( r.right, key, val ); // Tell a helper to insert (key,val) // into the right tree and give you // the solution. r.right = sol; // I can now solve the problem // but attaching the tree as my right // tree return (r); // return the solution. } } public Value get(Key key) { Node x; // Help variable /* -------------------------------------------- Find the node with key == "key" in the BST -------------------------------------------- */ x = root; // Always start at the root node while ( x != null ) { if ( key.compareTo( x.key ) < 0 ) { x = x.left; // Continue search in left subtree } else if ( key.compareTo( x.key ) > 0 ) { x = x.right; // Continue search in right subtree } else { // key == x.key, return the val in the node x return x.val; } } // "Key" Not found !! return null; } public void printnode(Node x, int h) { for (int i = 0; i < h; i++) System.out.print(" "); System.out.println("[" + x.key + "," + x.val + "]"); } void printBST() { showR( root, 0 ); } public void showR(Node t, int h) { if (t == null) return; showR(t.right, h+1); printnode(t, h); showR(t.left, h+1); } }