简体   繁体   中英

StackOverflow exception in findPath method

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, "");

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

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