惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
雷峰网
雷峰网
S
SegmentFault 最新的问题
博客园 - 【当耐特】
博客园_首页
量子位
爱范儿
爱范儿
博客园 - 叶小钗
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Jina AI
Jina AI
V
V2EX
美团技术团队
V
Visual Studio Blog
博客园 - 三生石上(FineUI控件)
IT之家
IT之家
Hugging Face - Blog
Hugging Face - Blog
Apple Machine Learning Research
Apple Machine Learning Research
小众软件
小众软件
博客园 - 聂微东
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Cloudflare Blog
宝玉的分享
宝玉的分享
WordPress大学
WordPress大学
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻

博客园 - NickyYe

DYNAMIC LINK LIBRARY - DLL 分布式系统中Unique ID 的生成方法 205. Isomorphic Strings 201. Bitwise AND of Numbers Range 189. Rotate Array 187. Repeated DNA Sequences 167. Two Sum II - Input array is sorted Convert BST to Greater Tree Uncommon Words from Two Sentences Delete Node in a BST Sliding Window Maximum Find K Closest Elements C++ TUTORIAL - MEMORY ALLOCATION - 2016 多线程 Console Event Handling SetConsoleCtrlHandler() -- 设置控制台信号处理函数 SetConsoleCtrlHandler 处理控制台消息 总结open与fopen的区别 LevelDB
Path Sum III
NickyYe · 2018-11-16 · via 博客园 - NickyYe

https://leetcode.com/problems/path-sum-iii

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

Return 3. The paths that sum to 8 are:

1.  5 -> 3
2.  5 -> 2 -> 1
3. -3 -> 11

解题思路:

这题虽然简单,写对了可不容易,想写出线性的方法更不容易。

简单的解法,一个个节点看。每个节点都往下找他的所有子节点,路径和为sum的,就算一个。

这样做的时间复杂度是O(n^2)。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int pathSum(TreeNode root, int sum) {
        int[] count = new int[1];
        count(root, sum, count);
        if (root != null) {
            count[0] += pathSum(root.left, sum);
            count[0] += pathSum(root.right, sum);
        }        
        return count[0];
    }
    
    public void count(TreeNode root, int sum, int[] count) {
        if (root == null) {
            return;
        }
        if (root.val == sum) {
            count[0]++;
        }
        if (root.left != null) {
            count(root.left, sum - root.val, count);            
        }
        if (root.right != null) {
            count(root.right, sum - root.val, count);
        }
    }
}

 这是一个大神的解法,可以做到o(n)的时间复杂度,也就是说每个结点只要遍历一遍就可以。

思路:

维护一个map,key是从root节点到每个节点的和,value是这个和出现过的次数。

在dfs的过程中,不断去构造这个map。可以想象,比如对于路径1,2,-1,-1,1,2。这样的和就是从1到每个节点的sum,即{1,3,2,1,2,4}。

假设目标是2。那么对于某个节点m,从root到它的和为x,我只要看m往前的和里面,有没有哪个节点n,从root到n的和为y,使得y+2=x。

实际上这个和为2的路径就是从y的下一个节点开始到x。

比如对于2这个节点,我们发现从root到它的和已经是4了,结果肯定不需要这么长的路径,就需要从root开始刨去一部分prefix。那么就可以刨去这两个prefix。

这个解法的巧妙之处在于,将前面的各种可能性的次数,注意是次数,存下来,而且这个次数是从root到我自己节点这个路径上的,这样我也不需要再递归或者回溯了。

如果是要返回所有的可能路径,而不是次数怎么办?

那么这个map可以改成下面,也就是存每个和的结束节点。利用这个就可以求出

        Map<Integer, List<TreeNode>> preSum2Nodes = new HashMap<Integer, List<TreeNode>>();
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int pathSum(TreeNode root, int sum) {
        Map<Integer, Integer> preSum2Count = new HashMap<Integer, Integer>();
        int[] count = new int[1];
        preSum2Count.put(0, 1);
        dfs(root, sum, 0, preSum2Count, count);
        return count[0];
    }
    
    public void dfs(TreeNode root, int sum, int curSum, Map<Integer, Integer> preSum2Count, int[] count) {
        if (root == null) {
            return;
        }
        curSum += root.val;
        //if (preSum2Count.getOrDefault(curSum - sum, 0) > 0) {
            //注意这里是curSum - sum,不是sum - curSum.
            count[0] += preSum2Count.getOrDefault(curSum - sum, 0);
        //}
        preSum2Count.put(curSum, preSum2Count.getOrDefault(curSum, 0) + 1);
        dfs(root.left, sum, curSum, preSum2Count, count);
        dfs(root.right, sum, curSum, preSum2Count, count);
        preSum2Count.put(curSum, preSum2Count.get(curSum) - 1);
    }
}