题目描述
给定一个二叉树的根节点 root
,和一个整数 targetSum
,求该二叉树里节点值之和等于 targetSum
的 路径 的数目。
路径 不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
示例 1:
输入:root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 输出:3 解释:和等于 8 的路径有 3 条,如图所示。
示例 2:
输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 输出:3
思路
回溯,没啥好说的;和leetcode-78. 子集-CSDN博客这些题都差不多
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def __init__(self):
self.res = 0
def find_road(self, root, score):
if score == 0:
self.res+=1
if root.left:
self.find_road(root.left, score-root.left.val)
if root.right:
self.find_road(root.right, score-root.right.val)
def pathSum(self, root, targetSum):
"""
:type root: TreeNode
:type targetSum: int
:rtype: int
"""
if not root:
return 0
self.find_road(root, targetSum-root.val)
if root.left:
self.pathSum(root.left, targetSum)
if root.right:
self.pathSum(root.right, targetSum)
return self.res
如果想要具体的路径,加个list用来存储中间路径,代码如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def __init__(self):
self.ans = 0
def pathSum(self, root, targetSum):
"""
:type root: TreeNode
:type targetSum: int
:rtype: int
"""
if not root:
return 0
sub_rode = [root.val]
self.find_rode(root,targetSum-root.val,sub_rode)
if root.left:
self.pathSum(root.left, targetSum)
if root.right:
self.pathSum(root.right, targetSum)
return self.ans
def find_rode(self,root,score,sub_rode):
if score==0:
# tmp =sub_rode[::]
self.ans+=1
if root.left:
sub_rode.append(root.left.val)
self.find_rode(root.left,score-root.left.val,sub_rode)
sub_rode.pop(-1)
if root.right:
sub_rode.append(root.right.val)
self.find_rode(root.right,score-root.right.val,sub_rode)
sub_rode.pop(-1)