Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.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_Tree_Numbers_Binary Tree - Fatal编程技术网

python中二进制数树的减法分支

python中二进制数树的减法分支,python,tree,numbers,binary-tree,Python,Tree,Numbers,Binary Tree,就像我有这个问题,我根本不知道怎么做。问题是这样的: 定义一个名为subt_tree()的递归函数,该函数接受一个二进制数树,并递归地从左分支中减去每个右分支的值。例如,如果 tree1 = (25,((10,4),(12,11))) 然后子树(tree1)将返回 (25-((10-4)-(12-11))=(25-(6-1))=(25-5)=20 所以本质上,我必须将每个元组转化为一个减法问题,然后求解 我试过这个: def subt_tree(bnt): """Takes a bnt

就像我有这个问题,我根本不知道怎么做。问题是这样的:

定义一个名为subt_tree()的递归函数,该函数接受一个二进制数树,并递归地从左分支中减去每个右分支的值。例如,如果

tree1 = (25,((10,4),(12,11)))
然后
子树(tree1)
将返回

(25-((10-4)-(12-11))=(25-(6-1))=(25-5)=20

所以本质上,我必须将每个
元组
转化为一个减法问题,然后求解

我试过这个:

def subt_tree(bnt):
    """Takes a bnt and recursively subtracts the value of each right branch from the left branch.

    bnt -> number"""
    if not isinstance(bnt,tuple):
        return 1
    else:
        return subt_tree(bnt[0]) - subt_tree(bnt[1])

但是我的else语句中肯定有错误,因为无论我输入什么,它都只返回0或1。

为什么不返回值本身呢?这毕竟是递归的基本情况

i、 e

如果返回1,则只能得到一组值,这些值由相互减去1组成

def subt_tree(bnt):
    if not isinstance(bnt,tuple):
        return bnt
    else:
        return subt_tree(bnt[0]) - subt_tree(bnt[1])