Path Sum I II III
来源:互联网 发布:dota2 a卡优化 编辑:程序博客网 时间:2024/05/22 08:23
这三道题做了一下午,要继续努力。。。
Path Sum I:
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root==null)return false;
if(sum-root.val==0 && root.left==null && root.right==null)return true;
return hasPathSum(root.left,sum-root.val) || hasPathSum(root.right,sum-root.val);
}
}
Path Sum II:
回溯法
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {List<Integer> curList=new ArrayList<>();
List< List<Integer>> res=new ArrayList<>();
helper(root,curList,res,sum,0);
return res;
}
public void helper(TreeNode root,List<Integer> curList,List<List<Integer>> res,int sum,int curVal){
if(root==null){
return;
}
curVal+=root.val;
curList.add(root.val);
if(root.left==null&&root.right==null&&curVal==sum){
res.add(new ArrayList(curList));
curList.remove(curList.size()-1);
return;
}
else{
helper(root.left,curList,res,sum,curVal);
helper(root.right,curList,res,sum,curVal);
}
curList.remove(curList.size()-1);
}
}
Path Sum III:
public class Solution {
public int pathSum(TreeNode root, int sum) {
if(root == null)
return 0;
return dfs(root, sum)+pathSum(root.left, sum)+pathSum(root.right, sum);
}
private int dfs(TreeNode root, int sum){
int res = 0;
if(root == null)
return res;
if(sum == root.val)
res++;
res+=dfs(root.left,sum - root.val);
res+=dfs(root.right,sum - root.val);
return res;
}
}
- Path Sum I II III
- [Leetcode] Path Sum I,II,III
- Leetcode--Path Sum I,II,III
- 【LeetCode】112,113,437. Path Sum I, II, III
- Path Sum I、II
- Path Sum I,II
- path-sum-i&ii
- path-sum i & ii
- Path Sum,Path Sum II,Path Sum III总结
- Combination Sum I,II,III
- LeetCode:Path Sum I &&II
- 【LeetCode】path-sum i&ii
- Combination Sum I II III 回溯法
- leetcode Combination Sum I/II/III/IV
- Combination sum I, II,III && Combination
- 112. Path Sum && 113. Path Sum II && 437. Path Sum III
- LeetCode题解:Path Sum I and II
- [projecteuler]Maximum path sum I,II
- 004——Binder 机制详解—Binder 本地框架
- pycharm快捷键
- 支付宝开发表设计 适用于 所有支付业务
- listview和imageview实现条目单选效果
- ubuntu下如何安装android studio
- Path Sum I II III
- iOS 10 新特性之openURL
- Kotlin(二)-->基础语法
- Ubuntu下使用SSH和FileZilla远程登陆
- 华为,计算给定时间的下一秒,java
- 队列写杨辉三角(拿两个队列写的。。。。
- MySql5.7.14存储表情字符报错Incorrect string value
- oracle创建与使用视图
- Java Web 学习路线