Q:

Java Binary Search Tree - size() method overflow

I'm trying to write a size() method for a Java Binary Search Tree. I've looked at various tutorials which suggest the following format for the size() method:
    //Constructor
    public BST() {
            root = null;
        }

        // Inner Node class
        private static class Node<E> {
            protected E element;
            protected Node<E> left, right;
            protected Node(E elem) {
                element = elem;
                left = null;
                right = null;
            }
        }

    public int size() {
            return size(root);
        }

        int size(Node node)
        {
            if (root == null) {
                return 0;
            }
            else {
            return (size(root.left) + 1 + size(root.right));
         }
        }

//Main method
    public static void main(String[] args) {

        BST<String> bag = new BST<String>();

        bag.add("Orange");
        bag.add("Apple");
        bag.add("Pear");

        System.out.println(bag.size());

    }

However, this is returning a stack overflow error and I'm not sure why. Any ideas where I'm going wrong? Many thanks.

A:

As has been mentioned in the comments, your method int size(Node node) takes an argument called node, but in the method body, it doesn't use node - but instead it uses root. This won't work, to have a recursive method you need to operate on the arguments. 
Replace every occurrence of the expression root inside the int size(Node node) method with node and it will work.

