Python中的深度优先搜索永远不会返回True

时间:2016-01-13 15:41:11

标签: python recursion depth-first-search

在树中搜索明确包含3的'3'时,代码将进入正确的“if语句”,但不返回True。那是为什么?

class Node:
    def __init__(self):
        self.value = None
        self.leftChild = None
        self.rightChild = None

def dfs(root, sought):

    print "root", root.value
    print "sought", sought.value

    if root.value == sought.value:
        print "inside root = sought"
        return True

    elif root.leftChild is not None and root.rightChild is not None:
        dfs(root.leftChild, sought)
        dfs(root.rightChild, sought)
        return False

我使用搜索值s创建的树如下:

n1 = Node()
n2 = Node()
n3 = Node()
n4 = Node()
n5 = Node()
n1.leftChild = n2
n1.rightChild = n5
n2.leftChild = n3
n2.rightChild = n4

n1.value=1
n2.value=2
n3.value=3
n4.value=4
n5.value=5

s = Node()
s.value=3

但输出却令人困惑。我预感到return True的缺乏与Python的递归性质有关吗?

> dfs(n1,s)
> root 1
> sought 3
> root 2
> sought 3
> root 3
> sought 3
> inside root = sought
> root 4
> sought 3
> root 5
> sought 3
> False

1 个答案:

答案 0 :(得分:3)

您需要返回递归调用的结果:

    res_a = dfs(root.leftChild, sought)
    res_b = dfs(root.rightChild, sought)
    return res_a or res_b