找到节点后,递归二叉树搜索未返回True

时间:2017-11-17 09:50:11

标签: python recursion tree binary-tree

myTree是python中代表二叉树的列表列表。对于列表中的每个列表,元素0表示指向左子节点的指针,元素1表示节点的值,元素2表示指向右子节点的指针。

myTree = [[1,50,2],[3,27,4],[9,62,10],[5,12,6],[7,35,8],[-1,9,-1],[-1,14,-1],[-1,28,-1],[-1,41,-1],[11,59,12],[13,71,-1],[-1,52,-1],[-1,60,-1],[-1,68,-1]]


def findNode(item,comparingNode):
    #print (comparingNode)
    comparingNode = myTree[comparingNode]
    if item == comparingNode[1]:
        print(comparingNode[1])
        return True #This is where it is supposed to return True

    elif item > comparingNode[1]:
        if comparingNode[2] != -1:
            print(comparingNode[0],comparingNode[1],comparingNode[2],"comp1")
            return findNode(item,comparingNode[2])
        else:
            return False

    else:
        if comparingNode[0] != -1: 
            print(comparingNode[0],comparingNode[1],comparingNode[2],"comp2")
            findNode(item,comparingNode[0])
        else:
            return False


    #print(comparingNode[1])




if findNode(9,0) == True:
    print("found")

运行时,它不会产生错误消息,程序完成。搜索已清楚地找到节点9,因为在运行时,它在末尾打印出9。但是,即使调试器说它访问了源代码行(第9行),该函数也不会返回True。

3 个答案:

答案 0 :(得分:0)

你忘记了在其他路径上的回归。这有效:

def findNode(item,comparingNode):
    #print (comparingNode)
    comparingNode = myTree[comparingNode]
    if item == comparingNode[1]:
        print(comparingNode[1])
        return True #This is where it is supposed to return True

    elif item > comparingNode[1]:
        if comparingNode[2] != -1:
            print(comparingNode[0],comparingNode[1],comparingNode[2],"comp1")
            return findNode(item,comparingNode[2])
        else:
            return False

    else:
        if comparingNode[0] != -1: 
            print(comparingNode[0],comparingNode[1],comparingNode[2],"comp2")
            return findNode(item,comparingNode[0])
        else:
            return False

答案 1 :(得分:0)

正如Willem在上面的评论中所说,行:

findNode(item,comparingNode[0])

应修改为:

return findNode(item,comparingNode[0])

输出将是:

1 50 2 comp2
3 27 4 comp2
5 12 6 comp2
9
found

答案 2 :(得分:0)

你刚忘了return

if comparingNode[0] != -1: 
    print(comparingNode[0],comparingNode[1],comparingNode[2],"comp2")
    **** findNode(item,comparingNode[0])
else:
    return False

另一个注意事项:您可以在不执行== True的情况下进行测试:

if findNode(9,0):
    print("found")