0

I am trying to build the path for value in huffman, but I am getting stackoverflow exception.

My code:

public String findPath(short target, int root, String path)
{
    String result;
    if (root < 0)
    {
        if ((result = findPath(target, root, path + '0')) == null) {
            result = findPath(target, root, path + '1');
        }
    }
    else {
        result = (target == this.LEAF_NODES[root]) ? path : null;
        System.out.println("? " + result);
    }

    return result;
}

java.lang.StackOverflowError
    at java.lang.AbstractStringBuilder.ensureCapacityInternal(Unknown Source)
    at java.lang.AbstractStringBuilder.append(Unknown Source)
    at java.lang.StringBuilder.append(Unknown Source)
    at com.server.network.Client.findPath(Client.java:551)
    at com.server.network.Client.findPath(Client.java:551)
    at com.server.network.Client.findPath(Client.java:551)
    at com.server.network.Client.findPath(Client.java:551)
    at com.server.network.Client.findPath(Client.java:551)
    at com.server.network.Client.findPath(Client.java:551)
    at com.server.network.Client.findPath(Client.java:551)
    at com.server.network.Client.findPath(Client.java:551)
    at com.server.network.Client.findPath(Client.java:551)
    at com.server.network.Client.findPath(Client.java:551)
    at com.server.network.Client.findPath(Client.java:551)

551 line is:

            if ((result = findPath(target, root, path + '0')) == null) {

Where could be the problem?

I start search:

String path = client.findPath((short)2563, -1, "");
Mindee
  • 11
  • 6
  • You never change your `root` so you will always go in the `if(root < 0)` and will always go in the `findPath(target, root, path + '0')` which does nothing but lengthen your `path`. It's a nice infinite circle that will always end in a `StackOverflow`. – Ben Apr 06 '18 at 10:35
  • Ahh yes. I didn't notice that. Thank you for pointing it out! – Mindee Apr 06 '18 at 10:37
  • Always risky to use recursion in java. Each call stores the previous context on the stack, and the stack is not very large, unless you configure otherwise – Stefan Emanuelsson Apr 06 '18 at 10:57
  • Is there any better alternatives for recursion? – Mindee Apr 06 '18 at 10:59

1 Answers1

0

I fixed it:

public String findPath(short target, int root, String path)
{
    String result;
    if (root < 0)
    {
        if ((result = findPath(target, this.INTERNAL_NODES[(-root << 1) + 0], path + '0')) == null) {
            result = findPath(target, this.INTERNAL_NODES[(-root << 1) + 1], path + '1');
        }
    }
    else {
        result = (target == this.LEAF_NODES[root]) ? path : null;
        System.out.println("? " + result);
    }

    return result;
}

INTERNAL_NODES array contains left and right nodes. It's length is LEAF_NODES.length * 2 - 2

Mindee
  • 11
  • 6