Python 3.4.3.:二进制字符串树中所有字符串长度的总和
因此,我需要定义一个名为Python 3.4.3.:二进制字符串树中所有字符串长度的总和,python,recursion,binary-tree,string-length,Python,Recursion,Binary Tree,String Length,因此,我需要定义一个名为total_len()的递归函数,它接受一个二进制字符串树并返回所有叶子的长度之和。因此,total_len(((“一”、“二”、“三”)、(“四”、“五”))应该返回19,total_len((“左”、“右”)应该返回9,total_len(“一片叶子”)应该返回8。我真的不知道从哪里开始,我知道我完全错了,但到目前为止我得到的是: def total_len(BST): """Takes a binary string tree and returns the
total_len()
的递归函数,它接受一个二进制字符串树并返回所有叶子的长度之和。因此,total_len(((“一”、“二”、“三”)、(“四”、“五”))
应该返回19,total_len((“左”、“右”)
应该返回9,total_len(“一片叶子”)
应该返回8。我真的不知道从哪里开始,我知道我完全错了,但到目前为止我得到的是:
def total_len(BST):
"""Takes a binary string tree and returns the sum of all the lengths of
of all the leaves.
BST->int"""
if isinstance(BST,tuple):
return total_len(len(BST[0][0])+total_len(len(BST[1][0])))
else:
return BST
你可以这样做:
def total_len(bst):
if isinstance(bst, tuple):
if bst == ():
return 0
else:
return total_len(bst[0]) + total_len(bst[1:])
else:
return len(bst)