CSC301: Put: Reassigning as we go back up [20/30] Previous pageContentsNext page

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

Here is the final code.

Software engineering: Once and only once. This code is much better than the look before you leap that we started with. (See also here).

Software engineering: Refactoring. Changing the structure of code without changing its meaning. (See also here).

Possible performance issue: we are re-assigning the fields in the tree as we go up. This work is not done by look before you leap approach.

Software engineering wins! Premature optimization is the source of many bugs!

Previous pageContentsNext page