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 and sum = 22 , 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1return
[ [5,4,11,2], [5,8,4,5] ]
解法一:
注意要弹出最后一个数。
public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<>(); if (root == null) return res; List<Integer> path = new ArrayList<>(); path.add(root.val); dfs(root, sum - root.val, path, res); return res; } private void dfs(TreeNode root, int sum, List<Integer> path, List<List<Integer>> res) { if (root == null) return; if (root.left == null && root.right == null && sum == 0) { res.add(new ArrayList<Integer>(path)); return; } if (root.left != null) { path.add(root.left.val); dfs(root.left,sum-root.left.val,path,res); path.remove(path.size() - 1); } if (root.right != null) { path.add(root.right.val); dfs(root.right,sum-root.right.val,path,res); path.remove(path.size() - 1); } } }
解法二:
这个看起来比较简单。
pathSum:
1、如果是null, 就返回
2、把当前node的值加到ArrayList里
3、如果当前节点是叶节点且等于余下的值时,加入res中
4、用归递左边和右边的节点
5、注意要去掉最后一个左叶节点才可以继续右叶节点
public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<List<Integer>>(); pathSum(root, sum, new ArrayList<Integer>(), res); return res; } void pathSum(TreeNode root, int sum, List<Integer> path, List<List<Integer>> res) { if (root == null) { return; } path.add(root.val); if (root.left == null && root.right == null && sum == root.val) { res.add(new ArrayList<Integer>(path)); } else { pathSum(root.left, sum - root.val, path, res); pathSum(root.right, sum - root.val, path, res); } path.remove(path.size() - 1); } }