以下是一个示例代码,用于按树的长度计算总路径数:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def count_paths(root):
if not root:
return 0
return count_paths_helper(root, 0)
def count_paths_helper(node, curr_sum):
if not node:
return 0
# 将当前节点的值加到当前路径的和中
curr_sum += node.val
# 如果当前路径的和等于树的长度,路径计数加1
paths = 1 if curr_sum == tree_length else 0
# 递归计算左子树和右子树中的路径数
paths += count_paths_helper(node.left, curr_sum)
paths += count_paths_helper(node.right, curr_sum)
return paths
# 创建一个示例树
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
# 计算树的长度
tree_length = 3
# 计算总路径数
total_paths = count_paths(root)
print("总路径数为:", total_paths)
在上述代码中,我们定义了一个TreeNode
类,用于表示树的节点。count_paths
函数是主要的计算函数,它接受根节点作为参数,并调用count_paths_helper
函数来递归计算路径数。
count_paths_helper
函数采用深度优先搜索的方式遍历树中的每个节点。它通过将当前节点的值加到当前路径的和中,并检查当前路径的和是否等于树的长度来判断是否找到了一条路径。如果是,则将路径计数加1。然后,它递归调用自身来计算左子树和右子树中的路径数,并将计数累加到paths
变量中。
最后,我们创建了一个示例树,并指定树的长度为3。然后调用count_paths
函数来计算总路径数,并将结果打印出来。
上一篇:按鼠标时记录数据列表的值