为什么我的函数在 return 之后没有终止?

Why is my function not terminating after return?

我正在使用字符串 "BANANA$" 创建后缀树。当以“print(findPath(root, "BANANA$", 5))”的形式从 main 调用我的 findPath 函数时,检查 "A$" 是否是来自根的路径,我得到以下输出:

SEQUENCE: A$
  CUR CHILD: $
    NON-MATCH: $ 0
  CUR CHILD: A
    CHILD MATCHED: A
    NEW SEQ: $

SEQUENCE: $
  CUR CHILD: $
REACHED THE END!
  CUR CHILD: BANANA$
  CUR CHILD: NA
False

它打印出 "REACHED THE END!" 行,很明显函数已经触及了那部分代码,但是为什么我的函数没有在 "return True" 行之后终止?

def findPath(curNode, sequence, i):

    sequence = sequence[i:]
    print("\nSEQUENCE: " + sequence)

    for child in curNode.children:
        print("  CUR CHILD:", child.val)
        # print(len(child.val), child.val)

        # NO WAY IT CAN BE A MATCH, SO SKIP
        if (len(child.val) > len(sequence)):
            pass

        # POSSIBILITY TO MATCH
        else:
            curInd = 0
            count = 0

            # CHECK IF child.val MATCHES THE BEGINNING OF sequence
            while (curInd < len(child.val)):
                if (child.val[curInd] != sequence[curInd]):
                    print("    NON-MATCH:", child.val[curInd], curInd)
                    count += 1

                curInd += 1

            # child.val MATCHES THE BEGINNING OF sequence
            if (count == 0):
                # AN EXACT MATCH, SO REACHED THE END
                if (child.val == sequence):
                    print("REACHED THE END!")
                    return True

                else:
                    print("    CHILD MATCHED:", child.val)
                    newInd = len(child.val)
                    sequence = sequence[newInd:]
                    print("    NEW SEQ:", sequence)
                    findPath(child, sequence, 0)
    return False

在递归调用 return 之后,parent 函数继续其 for loop。如果你想让它在 child 结束时停止,你需要检查递归的 return 值。

                else:
                    print("    CHILD MATCHED:", child.val)
                    newInd = len(child.val)
                    sequence = sequence[newInd:]
                    print("    NEW SEQ:", sequence)
                    if findPath(child, sequence, 0):
                        return True

这将通过递归堆栈传播 True 值。