简体   繁体   中英

How to fix Stack Overflow from recursive getHeight method

When I run my code for a method calculating the height of a binary search tree, it results in a Stack Overflow error, but only for trees with more than one node (BSTElements in my program). I have read that this is due to a faulty recursive call, but cannot identify the problem in my code.

public int getHeight() {

    return getHeight(this.getRoot());
}

private int getHeight(BSTElement<String,MorseCharacter> element) {

    int height=0;

    if (element == null) {
        return -1;
    }

    int leftHeight = getHeight(element.getLeft());
    int rightHeight = getHeight(element.getRight());

    if (leftHeight > rightHeight) {
        height = leftHeight;
    } else {
        height = rightHeight;
    }

    return height +1;
}

Here is full code:

public class MorseCodeTree {

private static BSTElement<String, MorseCharacter> rootElement;



public BSTElement<String, MorseCharacter> getRoot() {
    return rootElement;
}

public static void setRoot(BSTElement<String, MorseCharacter> newRoot) {
    rootElement = newRoot;
}



public MorseCodeTree(BSTElement<String,MorseCharacter> element) {
    rootElement = element;
}

public MorseCodeTree() {
    rootElement = new BSTElement("Root",  "", new MorseCharacter('\0', null));
}
    public int getHeight() {

    return getHeight(this.getRoot());
}

private int getHeight(BSTElement<String,MorseCharacter> element) {

    if (element == null) {
        return -1;
    } else {
        int leftHeight = getHeight(element.getLeft());
        int rightHeight = getHeight(element.getRight());


    if (leftHeight < rightHeight) {
        return rightHeight + 1;
    } else {
        return leftHeight + 1;
    }
    }
}
public static boolean isEmpty() {
        return (rootElement == null);   
}

public void clear() {
    rootElement = null;
}

public static void add(BSTElement<String,MorseCharacter> newElement) {

        BSTElement<String, MorseCharacter> target = rootElement;
        String path = "";
        String code = newElement.getKey();

        for (int i=0; i<code.length(); i++) {
            if (code.charAt(i)== '.') {
                if (target.getLeft()!=null) {
                    target=target.getLeft();
                } else {
                    target.setLeft(newElement);
                    target=target.getLeft();
                }

            } else {
                if (target.getRight()!=null) {
                    target=target.getRight();
                } else {
                    target.setRight(newElement);
                    target=target.getRight();
                }   
            }
        }
        MorseCharacter newMorseChar = newElement.getValue();

        newElement.setLabel(Character.toString(newMorseChar.getLetter()));
        newElement.setKey(Character.toString(newMorseChar.getLetter()));
        newElement.setValue(newMorseChar);

}

    public static void main(String[] args) {
    MorseCodeTree tree = new MorseCodeTree();
        BufferedReader reader;

    try {
        reader = new BufferedReader(new FileReader(file));
        String line = reader.readLine();


        while (line != null) {

            String[] output = line.split(" ");
            String letter = output[0];
            MorseCharacter morseCharacter = new MorseCharacter(letter.charAt(0), output[1]);

            BSTElement<String, MorseCharacter> bstElement = new BSTElement(letter, output[1], morseCharacter);

            tree.add(bstElement);

            line = reader.readLine();

            System.out.println(tree.getHeight());
        }
        reader.close();




    } catch (IOException e) {
    System.out.println("Exception" + e);
    }

There doesn't appear to be anything significantly wrong 1 with the code that you have shown us.

If this code is giving a StackOverflowException for a small tree, that most likely means that your tree has been created incorrectly and has a cycle (loop) in it. If your recursive algorithm encounters a cycle in the "tree" it will loop until the stack overflows 2 .

To be sure of this diagnosis, we need to see an MVCE which includes all code needed to construct an example tree that exhibits thie behavior.


1 - There is possibly an "off by one" error in the height calculation, but that won't cause a stack overflow.

2 - Current Java implementations do not do tail-call optimization.

Please, check at first if your tree is created incorrectly.

Otherwise, most probably, it's because of your height variable. When your program performs a recursive call, it always initiates as 0, resulting no possible output.

If you made a node class of yourself, like this one:

/* Class containing left and right child of current
node and key value*/

class Node {
    int element;
    Node left, right;

    Node(int item) {
        element = item;
        left = right = null;
    }

    Node(int item, Node left, Node right) {
        element = item;
        this.left = left;
        this.right = right;
    }
}

Then, your getHeight class should be like this:

int nodesHeightFinder(Node n) {

    if(n == null) return -1; /*As, if a tree has no nodes, it should not have any height.*/
    else {

        int heightOfLeftSubtree = nodesHeightFinder(n.left);
        int heightOfRightSubtree = nodesHeightFinder(n.right);

        if(heightOfLeftSubtree < heightOfRightSubtree) {
            return heightOfRightSubtree + 1;
        } else {
            return heightOfLeftSubtree + 1;
        }
    }
}

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM