437. Path Sum III(路径可以任意点开始,任意点结束)
2024-09-04 14:48:49
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1 Return 3. The paths that sum to 8 are: 1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
class Solution { public int pathSum(TreeNode root, int sum) {
if(root==null) return 0;
int res = path(root,sum)+pathSum(root.right,sum)+pathSum(root.left,sum);
return res; } private int path(TreeNode root, int sum) {
int res=0;
if(root==null)
return res ;
if(sum==root.val)
res+=1;
res+=path(root.left,sum-root.val);
res+=path(root.right,sum-root.val);
return res;
} }
最新文章
- .Net(c#)汉字和Unicode编码互相转换
- iOS通讯录整合,兼容iOS789写法,附demo
- 复利计算--结对项目<;04-11-2016>; 1.0.0 lastest 阶段性完工~
- .net 使用memcache做缓存
- cJSON_json包的C语言解析库
- CocoStudio基础教程(2)关联程序逻辑与cocoStudio导出文件
- wikioi 1203 判断浮点数是否相等
- EF6 在原有数据库中使用 CodeFirst 总复习(三、重建迁移)
- 将ubuntu14.04设置为文本模式启动?
- Tomcat普通用户部署教程(生产服务器)
- c#面向对象小结
- 洛谷 P2401 不等数列
- Ocelot-基于.NET Core的开源网关实现
- 分支界定( BRANCH-AND-BOUND)
- linux报错-bash: xhost: command not found
- 解决Tomcatt下连接数据库的classNoFount问题
- nginx部署django应用
- 配置vim
- 测试char,varchar存储
- grep命令相关用法
热门文章
- 成功抓取douban 所有电影
- Django - 安装wagtail
- Struts1中actionform和action属于MVC哪一层,为什么?
- 【BZOJ】3301: [USACO2011 Feb] Cow Line(康托展开)
- 【BZOJ】3404: [Usaco2009 Open]Cow Digit Game又见数字游戏(博弈论)
- javascript屏蔽浏览器右键功能按钮
- 常用的tagVARIANT结构【整理】
- Django admin 注册多个app
- ASP.NET Web API中的路由
- ubuntu 下 Nginx相关设置