首页 > 代码库 > [leetcode]Path Sum II
[leetcode]Path Sum II
Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.
For example:
Given the below binary tree andsum = 22
,5 / 4 8 / / 11 13 4 / \ / 7 2 5 1return
[ [5,4,11,2], [5,8,4,5]]
算法思路:
跟[leetcode]Path Sum区别不大,dfs
代码如下:
1 public class Solution { 2 List<List<Integer>> res = new ArrayList<List<Integer>>(); 3 public List<List<Integer>> pathSum(TreeNode root, int sum) { 4 if(root == null) return res; 5 List<Integer> list = new ArrayList<Integer>(); 6 dfs(list, root, sum); 7 return res; 8 } 9 public void dfs(List<Integer> list,TreeNode root,int sum){10 if(root.left == null && root.right == null && root.val == sum){11 list.add(sum);12 res.add(new ArrayList<Integer>(list));13 list.remove(list.size() - 1);14 return;15 }16 if(root.left != null){17 list.add(root.val);18 dfs(list, root.left, sum - root.val);19 list.remove(list.size() - 1);20 }21 if(root.right!= null){22 list.add(root.val);23 dfs(list, root.right, sum - root.val);24 list.remove(list.size() - 1);25 }26 }27 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。