某公司的机试,给定一棵树,一个目标值,求从根节点到叶子节点和为目标值的最长序列长度or路径。
输入:
第一行:m, target,表示节点数目和目标值
第二行:root, 表示根节点
接下来m行,每一行四个数字,前三个分别表示父亲节点、左儿子和右儿子(0表示不存在,节点标号从1开始),第4个数表示父节点的值。
输出:
最长路径
代码如下:
# 二叉树:求指定目标和下的最长的序列长度
from collections import defaultdict
m, targetNum = map(int, input().split())
root = int(input())
mat = defaultdict(list)
mat[0] = [0, 0, 0, 0]
for _ in range(m):
father, l, r, val = map(int, input().split())
mat[father] = [l, r, val]
res = []
path = []
def backsearch(nums, node, target, pathLength, tmp):
if not node: return
if not nums[node][0] and not nums[node][1] and nums[node][2] == target:
res.append(pathLength)
path.append(tmp)
if nums[node][0]: # 左儿子
backsearch(nums, nums[node][0], target - nums[node][2], pathLength + 1, tmp + [nums[node][0]])
if nums[node][1]: # 右儿子
backsearch(nums, nums[node][1], target - nums[node][2], pathLength + 1, tmp + [nums[node][1]])
backsearch(mat, root, targetNum, 1, [root])
if not res:
print(0)
else:
print(max(res))
print(path)
'''
9 6
1
1 2 3 -3
2 4 5 3
4 0 0 6
5 8 9 0
8 0 0 1
9 0 0 6
3 6 7 9
6 0 0 2
7 0 0 1
'''
Leetcode上也有三道这种题,分别是路径总和I,路径总和II和路径总和III,对应的也都可以用DFS、BFS方法求解