【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/

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