CSC403: Put: Left and Right [5/9] Previous pageContentsNext page

    public void put (int key) {
        if (root==null) {
            root = new Node (key);
        } else {
            put (root, key);
        }
    }
    private static void put (Node x, int key) {
        if (key < x.key) {
            if (x.left == null)
                x.left = new Node (key);
            else
                put (x.left, key);
        } else if (key > x.key) {
            if (x.right == null)
                x.right = new Node (key);
            else
                put (x.right, key);
        }
    }

Left and right.

Wow. Too many base cases!

Single method call responsible both for creating the node and for putting it in the right place.

Previous pageContentsNext page