path sum 系列

題號(hào) 112/113/437

pathsum III :http://www.itdecent.cn/p/400586f0a7c9


import java.util.*;

public class PathSum {

    /**
     *
     * pathSum:root --> leaf:看有沒有加起來 == sum的路徑
     *
     * dfs
     * */
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null) {
            return false;
        }

        if(root.left == null && root.right == null && sum == root.val) {
            return true;
        }

        return hasPathSum(root.left, sum-root.val) || hasPathSum(root.right, sum-root.val);
    }


    /**
     * pathSum ii:root --> leaf:返回所有 加起來 == sum的路徑
     *
     * 回溯
     * */
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> solution = new ArrayList<>();

        findSum(res, solution, root, sum);

        return res;
    }

    private void findSum(List<List<Integer>> result, List<Integer> solution, TreeNode root, int residual){
        if (root == null) {
            return;
        }

        residual -= root.val;
        solution.add(root.val);
        // 這里有必要解釋下為什么不把這個(gè)條件和上一個(gè)條件合并
        // 以 root==null,且 residual == root.val 作為終點(diǎn);
        // 因?yàn)檫@么寫,左右子樹會(huì)各來一遍,result會(huì)加入兩遍solution
        if (residual == 0 && root.left == null && root.right == null) {

            result.add(new ArrayList<>(solution));
        }

        findSum(result, solution, root.left, residual);
        findSum(result, solution, root.right, residual);
        solution.remove(solution.size()-1);
    }


    /**
     *
     * pathSum iii:只要路徑向下即可,不要求起終點(diǎn)為root和leaf:返回看加起來 == sum的路徑的個(gè)數(shù)
     *
     * 前綴和
     */
    public int pathSumIII(TreeNode root, int target) {
        if(root == null) {
            return 0;
        }

        Map<Integer, Integer> prefix = new HashMap<>();
        prefix.put(0, 1);

        return helper(root, target, prefix, 0);
    }

    private int helper(TreeNode root, int target, Map<Integer, Integer> prefix, int curSum) {
        if(root == null) {
            return 0;
        }

        int res = 0;
        curSum += root.val;

        // 此前存在路徑的個(gè)數(shù)(A點(diǎn) 和 當(dāng)前點(diǎn) 的差值是target,那么 A-當(dāng)前點(diǎn)是有效路徑)
        res += prefix.getOrDefault(curSum-target, 0);

        // 回溯
        prefix.put(curSum, prefix.getOrDefault(curSum, 0) + 1);
        res += helper(root.left, target, prefix, curSum);
        res += helper(root.right, target, prefix, curSum);
        prefix.put(curSum, prefix.getOrDefault(curSum, 0) - 1);

        return res;
    }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容