按照题意递归即可 因为要遍历每一个节点所以会存在重复遍历运行时间增加
class Solution:
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
res=[0]
def dfs(root,cursum):
if not root:
return
if cursum-root.val==0:
res[0]+=1
if root.left:
dfs(root.left,cursum-root.val)
if root.right:
dfs(root.right,cursum-root.val)
if not root:
return 0
stack = [root]
while stack:
node = stack.pop()
dfs(node,sum)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return res[0]