我必须做一个函数来计算在我的二叉搜索树中以W开头的单词数。现在,我的程序返回0,即使有一个单词以W开头
这是我的密码:
def countNodes(tree):
count = 0
if tree == None:
return count
if tree['left'] != None:
if tree['data'][1][0] == 'w' or tree['data'][1][0] == 'W':
return count+1
if tree['right'] != None:
if (tree['data'][1][0] == 'w' or tree['data'][1][0] == 'W'):
return count+1
countNodes(tree['left'])
countNodes(tree['right'])
return count
def main():
myTree = None #create an empty tree
#Create a tree with the nodes [20, 2, 25, 14, 1, 23, 75, 93, 74]
#Note that the add function always returns the root of the BST!
myTree = add(myTree, [20, "Jenna"])
myTree = add(myTree, [2, "Wendy"])
myTree = add(myTree, [25, "Layla"])
myTree = add(myTree, [14, "Robert"])
myTree = add(myTree, [1, "Jamie"])
myTree = add(myTree, [23, "Stephanie"])
myTree = add(myTree, [75, "Jay"])
myTree = add(myTree, [93, "Barbara"])
myTree = add(myTree, [74, "John"])
print(countNodes(myTree))
以基本情况为例,即没有树,然后返回0,否则检查单词是否以字母开头并在树的分支上递归。你知道吗
我建议您对检查值有一个额外的参数:
因此,您只需要更改递归函数行:
相反,请执行以下操作:
当您找到一个W时,您也不需要返回,您只需要迭代您的计数器:
这样你就知道你有多个以W开头的名字了
因为Node类的代码在与问题一起出现的代码中丢失了,我从here中取了一些,并根据提供的数据对其进行了调整:
上面代码中的
countNodes()
函数按预期工作并打印:请注意,
if tree.data[1][0].upper() == 'W':
足以测试“W”和“W”两种情况,并且向下分支到根本不存在的节点(当.left为None或.right为None)是没有意义的。这使得“countNodes()”的代码稍微短一些,并且更容易理解。你知道吗相关问题 更多 >
编程相关推荐