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 public void put(Key key, Value val) { root = put(root, key, val); } public Node put(Node x, Key key, Value val) { if ( x == null ) return new Node( key, val ); if ( key.compareTo( x.key ) < 0 ) { // (key value) goes in left subtree x.left = put( x.left, key, val ); } else if ( key.compareTo( x.key ) > 0 ) { // (key value) goes in rightsubtree x.right = put( x.right, key, val ); } else { // ( key == x.key, we replace value in x ) x.val = val; } return x; } public Value get(Key key) { Node curr_node; // Help variable /* -------------------------------------------- Find the node with key == "key" in the BST -------------------------------------------- */ curr_node = root; // Always start at the root node while ( curr_node != null ) { if ( key.compareTo( curr_node.key ) < 0 ) { curr_node = curr_node.left; // Continue search in left subtree } else if ( key.compareTo( curr_node.key ) > 0 ) { curr_node = curr_node.right; // Continue search in right subtree } else { // key == curr_node.key, return the val in the node curr_node return curr_node.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); } }