微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

leetcode 437. 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

解法1,DFS:
# DeFinition for a binary tree node.
# class TreeNode(object):
#     def __init__(self,x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def pathSum(self,root,sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: int
        # java solution
        public class Solution {
            public int pathSum(TreeNode root,int sum) {
                if (root == null) return 0;
                return pathSumFrom(root,sum) + pathSum(root.left,sum) + pathSum(root.right,sum);
            }

            private int pathSumFrom(TreeNode node,int sum) {
                if (node == null) return 0;
                return (node.val == sum ? 1 : 0) 
                    + pathSumFrom(node.left,sum - node.val) + pathSumFrom(node.right,sum - node.val);
            }
        }
        """
        def dfs(node,target):      
            if not node: return 0 
            return int(node.val == target)+dfs(node.left,target-node.val)+dfs(node.right,target-node.val)
        
        if not root: return 0
        return dfs(root,sum)+self.pathSum(root.left,sum)+self.pathSum(root.right,sum)

 尤其注意是dfs(root,sum) 而不是dfs+dfs+dfs!容易出错!

 

另外解法就是前缀树的解法,前缀树记录sum,比如:

root = [10,sum = 8

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

到节点3的前缀sum就是{10:1,15:1,18:1},则包括节点3的满足sum=8的路径就是{10,3}这条通路减去{10}这条通路,两个前缀相减,更深的前缀-浅的前缀就是中间路路径,18-10=8满足条件。

代码

# DeFinition for a binary tree node.
# class TreeNode(object):
#     def __init__(self,sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: int        
        """
        def traverse(node,total,pre_sum):
            if not node:
                return 0
            total += node.val
            ans = pre_sum.get(total-sum,0)
            pre_sum[total] = pre_sum.get(total,0)+1
            ans += traverse(node.left,pre_sum) + traverse(node.right,pre_sum)
            pre_sum[total] -= 1
            return ans
        
        return traverse(root,{0:1})        

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐