LeetCode437. Path Sum III (路径和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,000.

Example:

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

Reference Answer

Method one

DFS + DFS:

使用DFS解决。dfs函数有两个参数,一个是当前的节点,另一个是要得到的值。当节点的值等于要得到的值的时候说明是一个可行的解。再求左右的可行的解的个数,求和之后是所有的。

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: int
        """
# Method one: DFS + DFS
        if not root:
            return 0 
        return self.dfs(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum)


    def dfs(self, root, target):
        res = 0
        if not root:
            return res
        target -= root.val
        if target == 0:
            res += 1
        res += self.dfs(root.left, target)
        res += self.dfs(root.right, target)
        return res   

Method Two:

使用BFS找到每个顶点作为起点的情况下,用dfs计算等于sum的路径个数。

这里有个问题是,必须将root的空值也加入temp_node中,如下:

  while temp_node:
      node = temp_node.popleft()
      if not node:
          continue
      self.dfs(node, res, 0, sum)
      temp_node.append(node.left)
      temp_node.append(node.right)

若是修改为一下代码则不能通过:

 while temp_node:
     node = temp_node.popleft()
     self.dfs(node, res, 0, sum)
     if not node.left:
     	temp_node.append(node.left)
     if not node.right:
     	temp_node.append(node.right)

BFS + DFS

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: int
        """
# Method two: BDF + DFS
        if not root:
            return 0
        temp_node = collections.deque()
        res = [0]
        temp_node.append(root)
        while temp_node:
            node = temp_node.popleft()
            if not node:
                continue
            self.dfs(node, res, 0, sum)
            temp_node.append(node.left)
            temp_node.append(node.right)
        return res[0]
    
    
    def dfs(self, root, res, path, target):
        if not root: return
        path += root.val
        if path == target:
            res[0] += 1
        self.dfs(root.left, res, path, target)
        self.dfs(root.right, res, path, target)   

Note

  • 这种DFS+DFS及BFS+DFS的二叉树题其解题思路尤其值得注意!!!

参考文献

[1] https://blog.csdn.net/fuxuemingzhu/article/details/71097135

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/85063740