您的位置:首页 > 其它

(leetcode)Path Sum III 挺有意思的一题

2017-07-04 21:01 211 查看
原题地址 https://leetcode.com/problems/path-sum-iii/#/description

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.
中文大概就是说,给一个只包含整数的二叉树,找一条路径加起来等于一个确定的值,路径只能从上到下,可以从非根节点开始,可以到非叶节点结束,简单说任意从上到下。

------------------------------------------------------------------------------------------------------------------------------------------------------

留个分割线思考

主要思路用到了前缀和,比如一条路径A[2,3,4,-3,6,-2],前缀和[2,5,9,6,12,10],我要截取路径A的某一段,比如[3,4,-3]那么我要用前缀和6-2就得到了和。

因此我只要用个 先序遍历,每次计算终结于该节点的满足条件路径数的个数。则一个节点及其子树产生的路径数等于  以下3者相加

1.终止于该节点的路径个数

2.左子树的路径个数

3.右子树的路径个数

然后不难写出程序,这里用python 实现,c++ 自行用 unorder_map, java 用hashmap

# Definition for a binary tree node.    // 原文给的数据结构

# class TreeNode(object):

#     def __init__(self, x):

#         self.val = x

#         self.left = None

#         self.right = None

    def pathSum(self, root, sum):  //sum 是目标值,原文给的。。。。

        a={0:1}                    //  用字典保存路径   字典内置数据结构用哈希表实现的,和为0时,默认个数1。指前缀和的值刚好等于了目标值       

        cursum=0               //  计算到该节点的前缀和

        def dfs(cursum,node,a):

            if node is None:    

                return 0     

            cursum+=node.val      // 父节点值加改节点值 等于当前前缀和

            res=a.get(cursum-sum,0)   //    字典的get方法 如果不存在cursum-sum,则默认返回0,如果存在说明,说明存在这样的路径。得到终止于该节点的个数

            a[cursum]=a.get(cursum,0)+1    // 将字典中该路径的个数加1

            res=res+dfs(cursum,node.left,a)+dfs(cursum,node.right,a)   // 参考前面说的内容  1.2.3

            a[cursum]=a[cursum]-1           //因为 左右子树已访问完,所以要把 前面 加上的路径 去掉,这条路已经不通!!

            return res                                //返回 由该节点及其子树产生的路径个数

        return dfs(0,root,a)              
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息