当前位置:网站首页>Interview Question 04.12. Summation Path-dfs+Auxiliary Array Method
Interview Question 04.12. Summation Path-dfs+Auxiliary Array Method
2022-08-10 18:33:00 【Mr Gao】
面试题 04.12. 求和路径
给定一棵二叉树,其中每个节点都含有一个整数数值(该值或正或负).设计一个算法,打印节点数值总和等于某个给定值的所有路径的数量.注意,路径不一定非得从二叉树的根节点或叶节点开始或结束,但是其方向必须向下(只能从父节点指向子节点方向).
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
3
解释:和为 22 的路径有:[5,4,11,2], [5,8,4,5], [4,11,7]
The code for solving this problem is as follows,Still a good topic,It is recommended not to use the brute force solution directly:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */
int count;
void dfs(struct TreeNode*root,int sum,int val,int *r,int h){
if(root){
r[h]=root->val;
if(root->left){
dfs(root->left,sum,root->val+val,r,h+1);
}
if(root->right){
dfs(root->right,sum,root->val+val,r,h+1);
}
int eval=root->val+val;
if(eval==sum){
count++;
}
for(int i=0;i<h;i++){
eval=eval-r[i];
if(eval==sum){
count++;
}
}
}
}
int pathSum(struct TreeNode* root, int sum){
int *r=(int *)malloc(sizeof(int)*1000);
count=0;
dfs(root,sum,0,r,0);
return count;
}
边栏推荐
- 钻石价格预测的ML全流程!从模型构建调优道部署应用!
- 五菱宏光MINI EV,唯一的缺点就是安全性
- LeetCode 198:打家劫舍
- Toronto Research Chemicals BTK抑制剂丨ACP-5197
- 痛苦的四大原因
- Active users of mobile banking grew rapidly in June, hitting a half-year high
- 如何通过JMobile软件实现虹科物联网HMI/网关的报警功能?
- CSV(Comma-Separate-Values)逗号分隔值文件
- Toronto Research Chemicals农药检测丨甲硫威
- Kong自定义插件初体验
猜你喜欢

从Delta 2.0开始聊聊我们需要怎样的数据湖
![[Image dehazing] Image dehazing based on color attenuation prior with matlab code](/img/ae/d6d36671804fadae548464496f28d6.png)
[Image dehazing] Image dehazing based on color attenuation prior with matlab code

「POJ 3666」Making the Grade 题解(两种做法)

【HMS core】【FAQ】AR Engine、Analytics Kit、Video Editor Kit、Image Kit、Map Kit典型问题合集2

6月各手机银行活跃用户较快增长,创半年新高

开发模式对测试的影响

欧洲核子研究中心首次在量子机器学习研究中取得实效

H3C_堆叠(IRF)及链路聚合在项目中的综合应用

接口测试进阶接口脚本使用—apipost(预/后执行脚本)

NPDP|传统行业产品经理如何进行能力提升?
随机推荐
Scala中使用 Jackson API 进行JSON序列化和反序列化
Intelligent bid strategy how to affect advertising effectiveness?
直播回顾|多云时代,如何建设企业级云管理平台?(附建设指南下载)
海思HI3516DV300开发资料
WebRTC源码分析 nack详解
Keil5退出仿真调试卡死的解决办法
组合模式
网络可观测性:让您的网络监控更上一层楼|TechGenix
机器人控制器编程实践指导书旧版-实践五 数字舵机(执行器)
哈夫曼实现文件压缩解压缩(c语言)
容器化 | 在 S3 实现定时备份
三星Galaxy Watch5产品图片流出 非Pro表款亦有蓝宝石加持
报告详解影响英特尔10/11/12代酷睿处理器的ÆPIC Leak安全漏洞
Mysql index, transaction and storage engine
NPDP|传统行业产品经理如何进行能力提升?
Toronto Research Chemicals 对乙酰氧基苯乙酮说明书
Kong自定义插件初体验
Mysql索引、事务与存储引擎
const的自己理解
想玩转监控神器Prometheus吗?