113. 路径总和 II/面试题34. 二叉树中和为某一值的路径(简单)
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
1 2 3 4
| [ [5,4,11,2], [5,8,4,5] ]
|
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-ii
思路:
和路径总和3一样,只不过不是输出路径个数了,要将路径全部输出出来
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| class Solution { List<List<Integer>> res; List<Integer> list = new ArrayList<>(); public List<List<Integer>> pathSum(TreeNode root, int targetSum) { res = new ArrayList<>(); if(root==null){ return res; } list.add(root.val); backtrack(root,targetSum-root.val); return res; } public void backtrack(TreeNode root,int targetSum){ if(root.left==null && root.right==null && targetSum==0){ res.add(new ArrayList<>(list)); return; } if(root.left!=null){ list.add(root.left.val); targetSum -= root.left.val; backtrack(root.left,targetSum); targetSum += root.left.val; list.remove(list.size()-1);
}
if(root.right!=null){ list.add(root.right.val); targetSum -= root.right.val; backtrack(root.right,targetSum); targetSum += root.right.val; list.remove(list.size()-1); } return; } }
|
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
class Solution { LinkedList<List<Integer>> outlist = new LinkedList<>(); LinkedList<Integer> outpath = new LinkedList<>(); public List<List<Integer>> pathSum(TreeNode root, int sum) { PathSumhelper(root,sum); return outlist; } public void PathSumhelper(TreeNode root,int sum){ if(root==null) return; outpath.add(root.val); if(sum==root.val && root.left==null && root.right==null) outlist.add(new LinkedList(outpath)); PathSumhelper(root.left,sum-root.val); PathSumhelper(root.right,sum-root.val); outpath.removeLast(); } }
|