1. 程式人生 > >LeetCode113. 路徑總和 II

LeetCode113. 路徑總和 II

題目

給定一個二叉樹和一個目標和,找到所有從根節點到葉子節點路徑總和等於給定目標和的路徑。

說明: 葉子節點是指沒有子節點的節點。

示例: 給定如下二叉樹,以及目標和 sum = 22

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

返回:

[
   [5,4,11,2],
   [5,8,4,5]
]

分析

和上一道 路徑總和I 差不多,記錄一下路徑,不要提前退出。

記錄路徑的時候把數字新增進去了之後,記得取出來。

emmmmm千萬不要把templist給清空

程式碼  

/**
 * 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>> list = new ArrayList<List<Integer>>();
        List<Integer> tempList = new ArrayList<Integer>();        
        path(root,sum,list,tempList);        
        return list;
    }
    
    public static void path(TreeNode root, int sum,List<List<Integer>> list, List<Integer> tempList){
        if (root == null) return;
        if (sum-root.val == 0 && root.right == null && root.left == null){
            ArrayList<Integer> newlist = new ArrayList<Integer>(tempList);
            newlist.add(root.val);
            list.add(newlist);
        }
        tempList.add(root.val);
        
        if(root.left != null)
            path(root.left, sum-root.val,list,tempList);
        
        if (root.right != null)
            path(root.right, sum-root.val, list, tempList);
        
        tempList.remove(tempList.size()-1);
    }
    
}

週四打卡