- LeetCode | 面试题 04.12. 求和路径【Pytho
- LeetCode-python 面试题 04.12. 求和路径
- Leetcode-面试题 02.05 链表求和
- LeetCode | 面试题34. 二叉树中和为某一值的路径【剑
- Leetcode Path sum 路径求和III II
- LeetCode | 0491. Increasing Subs
- LeetCode | 1395. Count Number of
- LeetCode 面试题 17.13. 恢复空格 | Pytho
- LeetCode 面试题 08.03. 魔术索引 | Pytho
- LeetCode 面试题 08.03. 魔术索引 | Pytho
问题
给定一棵二叉树,其中每个节点都含有一个整数数值(该值或正或负)。设计一个算法,打印节点数值总和等于某个给定值的所有路径的数量。注意,路径不一定非得从二叉树的根节点或叶节点开始或结束,但是其方向必须向下(只能从父节点指向子节点方向)。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
3
解释:和为 22 的路径有:[5,4,11,2], [5,8,4,5], [4,11,7]
提示:
- 节点总数 <= 10000
思路
递归
因为不一定是从根节点开始,所以要递归左右子树,从左右子树根节点开始向下。
代码
Python3
# 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:
if not root:
return 0
return self.dfs(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum)
def dfs(self, root, sum):
# 要特判为空,否则下面 sum == root.val 会报错
if not root:
return 0
res = 0
if sum == root.val:
res += 1
res += self.dfs(root.left, sum - root.val)
res += self.dfs(root.right, sum - root.val)
return res
网友评论