【LeetCode】437. 路径求和(三)

问题描述

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.

给定一个二叉树,其中每个节点都包含一个整数值。
找出与给定值相加的路径数。
路径不需要在根节点或叶节点处开始或结束,但必须向下(只从父节点移动到子节点)。
树的节点不超过1,000个,值的范围是-1,000,000到1,000,000。

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

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

返回 3. 

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

 

Python 实现

题目要求的是路径必须从上到下,从祖先到后代,因此可以利用 BFS (深度优先搜索)的思路来遍历二叉树。

代码中定义了两个方法:pathSum 和 pathFrom。前者是从 sum 开始,以当前节点作为根节点出发遍历子树;后者是从剩余的数值 val 开始,以当前节点作为根节点出发遍历子树。因此,通过 pathFrom 实现了 BFS,伴随着 sum 的减少;通过 pathSum 实现子树根节点递归调用,以 sum 值在每个节点启动实现 BFS。从而考虑到题目要求的各种情况。

# 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
        """
        
        # DFS
        if root == None:
            return 0
        return self.pathFrom(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum)
        
    def pathFrom(self, node, val):
        if node == None:
            return 0
        
        cnt = self.pathFrom(node.left, val - node.val) + self.pathFrom(node.right, val - node.val)
        if node.val == val:
            cnt += 1
        return cnt

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章