[LeetCode]113. 路徑總和 II

題目

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

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

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

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

返回:

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

解題思路

詳細思路請參考 劍指 Offer 34. 二叉樹中和爲某一值的路徑

代碼

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        if(root == null){
            return res;
        }
        LinkedList<Integer> path = new LinkedList<>();
        dfs(root, 0, sum, path);
        return res;
    }

    private void dfs(TreeNode root, int curSum, int sum, LinkedList<Integer> path){
        curSum += root.val;
        path.offerLast(root.val);
        if(curSum == sum && root.left == null && root.right == null){
            res.add(new LinkedList(path));
        }
        if(root.left != null){
            dfs(root.left, curSum, sum, path);
        }
        if(root.right != null){
            dfs(root.right, curSum, sum, path);
        }
        path.removeLast();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章