[leetcode] 113. 路徑總和 II
阿新 • • 發佈:2018-11-06
這題跟上個題的區別112. 路徑總和,需要儲存下路徑,且有可能出現多條路徑。
在前一個題的基礎上加上回溯即可
class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> ansList = new ArrayList<>(); if (root == null) return ansList; List<Integer> curList = new ArrayList<>(); findPath(root, sum, curList, ansList); return ansList; } private void findPath(TreeNode root, int sum, List<Integer> curList, List<List<Integer>> ansList) { if (root == null) return; curList.add(root.val); if (root.left == null && root.right == null && sum == root.val) { List<Integer> tmp = new ArrayList<>(curList); ansList.add(tmp); } else { findPath(root.left, sum - root.val, curList, ansList); findPath(root.right, sum - root.val, curList, ansList); } curList.remove(curList.size() - 1); } }