Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在树中查找路径的和_Python_Python 2.7 - Fatal编程技术网

Python 在树中查找路径的和

Python 在树中查找路径的和,python,python-2.7,Python,Python 2.7,我正在尝试创建一个函数,用于测试是否有一条路径与我的值相加sum1。我不确定为什么我的函数是错误的,但我从输出中假设它运行了太多次。我的树在最初几次递归运行时似乎工作正常,但随着它越来越深入递归,它似乎做得太多了 输入: hasPathSum(r,20) 输出: has Path sum? 12 7 5 False 我的职能: def hasPathSum(root,sum1): # Given a tree and a sum, return true if there is a p

我正在尝试创建一个函数,用于测试是否有一条路径与我的值相加
sum1
。我不确定为什么我的函数是错误的,但我从输出中假设它运行了太多次。我的树在最初几次递归运行时似乎工作正常,但随着它越来越深入递归,它似乎做得太多了

输入:

hasPathSum(r,20)

输出:

has Path sum?
12
7
5
False
我的职能:

def hasPathSum(root,sum1):
    # Given a tree and a sum, return true if there is a path from the root
    # down to a leaf, such that adding up all the values along the path
    # equals the given sum
    # Strategy: Subtract the node value from the sum when recurring down,
    # and check to see if the sum is 0 when you run out of tree
    if not root:   # negative values? make sum == 0?
        return False
    else:
        sum1 = sum1 - root.value
        if sum1 == 0:
            return True
        else:
            if root.left is not None:
                print sum1
                return hasPathSum(root.left, sum1)
            if root.right is not None:
                print sum1
                return hasPathSum(root.right, sum1)
        return False
我的树:

r = Node(8)

#left

a = Node(5)
b = Node(2)
c = Node(1)
d = Node(3)
e = Node(7)

#right


f = Node(14)
g = Node(11)
h = Node(10)
i = Node(15)
j = Node(19)
k = Node(20)
l = Node(21)

BST_Insert(r, a)
BST_Insert(r, b)
BST_Insert(r, c)
BST_Insert(r, d)
BST_Insert(r, e)
BST_Insert(r, f)
BST_Insert(r, g)
BST_Insert(r, h)
BST_Insert(r, i)
BST_Insert(r, j)
BST_Insert(r, k)
BST_Insert(r, l)

当您递归到左/右路径时,您正在丢弃返回value@fileoffset我明白你的意思。我看到我的flaw@fileoffset我向递归函数添加了返回值,但仍然得到了相同的输出=/一个小点:
如果root为None:
root
为任何类型的假值时,将失败,因为
[]为None
为False
<代码>is
检查标识是否不相等。您的语句是“if root与object None相同”,而您可能想要“if root是一个假值”,比如说一个空字符串,一个不同的对象。如果不是root,则应将条件更改为
;或者更具体地说,如果不是hasattr(root,“left”)或hasattr(root,“right”):
您的编辑将不起作用,因为如果一个节点同时具有左和右节点,它将只计算左并返回该值。您应该具有如下内容:
返回hasPathSum(root.left,sum1)或hasPathSum(root.right,sum1)