思想:
- 树的遍历:选用中序遍历
- 记录下从下到上的路径和,包括从非节点开始
- 如何记录从非叶节点开始,向上传递的过程中,将自身节点也向上传递。
- 如何记录路径和:将自身节点的值,加上左右子树传递过的列表的值,最后加上自身的值,并向上传递
- 遍历过程中,记录一共有多少个和为sum
# 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: TreeNode, sum: int) -> int:
re = 0
def midOrder(root: TreeNode):
nonlocal re
if not root:
return []
reList = [root.val] + [v+root.val for v in midOrder(root.left) +midOrder(root.right)]
for v in reList:
re += 1 if v == sum else 0
return reList
midOrder(root)
return re