LeetCode437. Path Sum III (路徑和III)
阿新 • • 發佈:2019-01-07
原題
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