給定一個二叉樹和一個目標和,找到全部從根節點到葉子節點路徑總和等於給定目標和的路徑。node
說明: 葉子節點是指沒有子節點的節點。spa
示例:
給定以下二叉樹,以及目標和 sum = 22,code
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
返回:遞歸
[ [5,4,11,2], [5,8,4,5] ]
這道題目是上一道的延伸,可是須要記錄下路徑,返回回去。這就是一個典型的backtrack的題目了。咱們用迭代的方式須要記錄中間的路徑狀態,稍顯複雜,因此咱們想用遞歸的方式來解,先探索左子樹,而後探索右子樹。若是都探索完以後,右知足的就加入到最終結果中。rem
public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new LinkedList<>(); helper(root, sum, res, new LinkedList<>()); return res; } public void helper(TreeNode root, int sum, List<List<Integer>> res, List<Integer> current) { if (root == null) { return; } current.add(root.val); if (root.left == null && root.right == null && sum == root.val) { // leaf node. res.add(new LinkedList<>(current)); // back track. current.remove(current.size() - 1); return; } helper(root.left, sum - root.val, res, current); helper(root.right, sum - root.val, res, current); // back track. current.remove(current.size() - 1); } }
手撕代碼QQ羣:805423079, 羣密碼:1024get