加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Path Sum III

发布时间:2020-12-14 04:30:46 所属栏目:大数据 来源:网络整理
导读: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 mu

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.

Example:

root = [10,5,-3,3,2,null,11,-2,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,count);
        }
    }
}

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

思路:

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

在dfs的过程中,不断去构造这个map。可以想象,比如对于路径1,-1,1,2。这样的和就是从1到每个节点的sum,即{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,0,preSum2Count,count);
        return count[0];
    }
    
    public void dfs(TreeNode root,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,curSum,count);
        dfs(root.right,count);
        preSum2Count.put(curSum,preSum2Count.get(curSum) - 1);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读