Python Leetcode二叉树求解最长路径问题

某公司的机试,给定一棵树,一个目标值,求从根节点到叶子节点和为目标值的最长序列长度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方法求解

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值