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 1
return
[ [5,4,11,2], [5,8,4,5] ]DFS的模板题,在叶子节点的时候进行条件的终止和判断,如果输入是一个null那么直接返回作为corner case,需要注意一下这种情况。
public List<List<Integer>> pathSum(TreeNode root, int sum) { List<Integer> list = new ArrayList<Integer>(); List<List<Integer>> result = new ArrayList<List<Integer>>(); dfs(root, sum, list, result); return result; } private void dfs(TreeNode root, int sum, List<Integer> list, List<List<Integer>> result) { if(root == null) return; // invalid case list.add(root.val); if(root.left == null && root.right == null) { // left node if(sum-root.val == 0) { result.add(new ArrayList<Integer>(list)); } } else if(root.left == null && root.right != null) { dfs(root.right, sum - root.val, list, result); } else if(root.left != null && root.right == null) { dfs(root.left, sum - root.val, list, result); } else { dfs(root.left, sum - root.val, list, result); dfs(root.right, sum - root.val, list, result); } list.remove(list.size() - 1); }
没有评论:
发表评论