题目:
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 1
return
[ [5,4,11,2], [5,8,4,5] ]
思路:注意前序遍历,返回前面一个状态,递归
代码:
public class Solution { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { ArrayList<Integer> list = new ArrayList<Integer>(); paths(root, sum, list); return res; } private void paths(TreeNode root, int sum, ArrayList<Integer> list){ if(root == null) return; if(root.left == null && root.right == null && sum - root.val == 0){ list.add(root.val); res.add(new ArrayList<Integer>(list)); list.remove(list.size() - 1); return; } list.add(root.val); paths(root.left, sum - root.val, list); paths(root.right, sum - root.val, list); list.remove(list.size() - 1); } }
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 1
return
[ [5,4,11,2], [5,8,4,5] ]