112. Path Sum && 113. Path Sum II
来源:互联网 发布:windows邮件服务器搭建 编辑:程序博客网 时间:2024/05/11 23:32
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
都是用dfs解决,不同的是112只要求判断是否存在path sum,113要求返回所有可能的path sum。
public class Solution { public boolean hasPathSum(TreeNode root, int sum) { if(root == null ) return false; return hasPath(root, sum); } public boolean hasPath(TreeNode root, int sum){ if(root.left == null && root.right == null && root.val == sum) return true; //叶子节点 if(root.left != null && hasPath(root.left,sum-root.val))return true; if(root.right != null && hasPath(root.right,sum-root.val))return true; return false; }}
public class Solution { List<List<Integer>> r = new ArrayList<List<Integer>>(); public List<List<Integer>> pathSum(TreeNode root, int sum) { if(root == null ) return r; List<Integer> tmp = new ArrayList<Integer>(); hasPath(root, sum,tmp); return r; } public void hasPath(TreeNode root, int sum , List<Integer> tmp){ if(root.left == null && root.right == null && root.val == sum) { //叶子节点 tmp.add(root.val); r.add(new ArrayList<Integer>(tmp)); tmp.remove(tmp.size()-1); return; }; tmp.add(root.val); //dfs if(root.left != null){ hasPath(root.left, sum-root.val , tmp); } if(root.right != null){ hasPath(root.right, sum-root.val , tmp); } tmp.remove(tmp.size()-1); }}
0 0
- 112. Path Sum && 113. Path Sum II
- 112. Path Sum&113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 设计师配色宝典!教你从零开始学配色(一)
- 开发之工厂模式
- Android 开发系列(3) - native代码调用java代码出现attempt using stale local reference错误及解决办法
- virgo tomcat下载
- MyBatis 多表联合查询及优化
- 112. Path Sum && 113. Path Sum II
- Android属性动画(二)之插值器与估值器
- xcode中打开lua代码有色差
- 极客学院VIP视频免费分享
- iOS开发之字符串显示不同的颜色
- MySQL配置文件详解
- Seesaw v2了解
- EasyMock 使用方法与原理剖析
- MySQL 机制图、innodb存储引擎图