简体   繁体   English

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

[英]Depth-first search in Python never returns True

When searching for a '3' in a tree that clearly contains a 3, the code will go into the correct "if statement", but does not return True.在明确包含 3 的树中搜索 '3' 时,代码将进入正确的“if 语句”,但不返回 True。 Why is that?这是为什么?

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

The tree that I created with the sought value s is as follows:我用寻求的值 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

But the output is befuddling.但输出令人眼花缭乱。 I have a hunch the lack of return True has something to do with Python's recursive nature?我有一种预感,缺少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

You need to return the results from your recursive calls:您需要返回递归调用的结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM