简体   繁体   中英

adding return case to recursive function

When it comes to recursion, here is where I struggle, I know the edge case for when the function should be true, but because I have to add a return false statement as well, and somewhere deep in the call stack, it does become true(which is the whole point of examining!), I want the final outcome to be true, and for the recursion to stop. But eventually, it finds its way to the return false, simply because its the last thing the function does.

public boolean isPathHelper(Node node, String input){
    if(node.accept == true){
        return true;
    }else{
        if(input.length() == 0){
            return false;
        }
        isPathHelper(getNextState(node, input.charAt(0) -'0'), input.substring(1));
        return false;
    }

How do I deal with this scenario? I know global variables can help, but I was hoping there's a gap in my knowledge instead.

Try this:

public boolean isPathHelper(Node node, String input, int count){
    if(input.length() == 0){
        return false; //I can't go any further: return "failed"
    }
    else if(count == input.length()){
        return true; //if I ever reach here, then I am done: return "success"
    }
    // else call self recursively
    return isPathHelper(
      getNextState(node, input.charAt(0) -'0'), input.substring(1), count+1);
}

Just examine your logic and your data carefully enough to be SURE you hit "count == input.length()" at some point. Preferably at some point before you run out of stack ;)

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