其他分享
首页 > 其他分享> > 【LeetCode】【HOT】437. 路径总和 III(前缀和+DFS)

【LeetCode】【HOT】437. 路径总和 III(前缀和+DFS)

作者:互联网

【LeetCode】【HOT】437. 路径总和 III

文章目录

在这里插入图片描述
在这里插入图片描述

package hot;

import java.util.HashMap;
import java.util.Map;

class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int val){
        this.val = val;
    }
}

public class Solution437 {
    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(10);
        TreeNode node2 = new TreeNode(5);
        TreeNode node3 = new TreeNode(-3);
        TreeNode node4 = new TreeNode(3);
        TreeNode node5 = new TreeNode(2);
        TreeNode node6 = new TreeNode(11);
        TreeNode node7 = new TreeNode(3);
        TreeNode node8 = new TreeNode(-2);
        TreeNode node9 = new TreeNode(1);
        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.right = node6;
        node4.left = node7;
        node4.right = node8;
        node5.right = node9;
        Solution437 solution = new Solution437();
        System.out.println(solution.method(node1, 8));
    }

    int ans;
    int t;
    Map<Integer, Integer> map = new HashMap<>();

    private int method(TreeNode root, int t){
        if(root == null) return 0;
        this.t = t;
        map.put(0, 1);
        dfs(root, root.val);
        return ans;
    }

    private void dfs(TreeNode root, int val){
        if(map.containsKey(val-t)){
            ans += map.get(val-t);
        }
        map.put(val, map.getOrDefault(val, 0) + 1);

        if(root.left != null){
            dfs(root.left, val + root.left.val);
        }

        if(root.right != null){
            dfs(root.right, val + root.right.val);
        }
        map.put(val, map.getOrDefault(val, 0) - 1);
    }
}

//时间复杂度为 O(n)
//空间复杂度为 O(n)

标签:map,right,TreeNode,val,DFS,HOT,new,437,root
来源: https://blog.csdn.net/qq_45593575/article/details/122672342