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分开处理。要小心叶子节点那里允许加个别点的时候,加完result也要remove!所有crt buffer里面的add 和 remove操作必须同时搭配!!
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> result = new ArrayList<>(); List<Integer> crt = new ArrayList<>(); dfs(root, sum, crt, result); return result; } private void dfs(TreeNode root, int dist, List<Integer> crt, List<List<Integer>> result) { if (root == null) { return; } if (root.left == null && root.right == null && root.val == dist) { crt.add(root.val); result.add(new ArrayList<Integer>(crt)); // 千万小心这里也得remove!! crt.remove(crt.size() - 1); return; } crt.add(root.val); dfs(root.left, dist - root.val, crt, result); dfs(root.right, dist - root.val, crt, result); crt.remove(crt.size() - 1); } }