响应式网站模板百度云网络营销主要是学什么的
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
给你二叉树的根节点
root
和一个整数目标和targetSum
,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
官方题解:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
代码如下:
class Solution {public List<List<Integer>> pathSum(TreeNode root, int targetSum) {List<List<Integer>> res = new ArrayList<>();if(root == null) {return res;}List<Integer> path = new ArrayList<>();path.add(root.val);targetSum -= root.val;dfs(root,targetSum,path,res);return res;}public void dfs(TreeNode root,int sum,List<Integer> path,List<List<Integer>> res){if(root.left == null && root.right == null && sum == 0){res.add(new ArrayList<>(path));return;}if(root.left != null) {path.add(root.left.val); sum -= root.left.val;dfs(root.left,sum,path,res);sum += root.left.val;path.remove(path.size()-1);}if(root.right != null) {path.add(root.right.val); sum -= root.right.val;dfs(root.right,sum,path,res);sum += root.right.val;path.remove(path.size()-1);}}
}