Description
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
分析
题目的意思是:在二叉树找出路径的和为sum值的所有路径,路径不需要从根结点到叶子节点。
- 解题方法还是递归,递归注意终止条件,返回条件,递归的条件就行了。很显然这道题有三种方式,即向左,从根结点,向右。所以总数为这三种方式的和。注意如果当前求和等于给定的sum后也可以继续递归的,所以注意返回条件。
C++实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
if(!root) return 0;
return getSum(root,0,sum)+pathSum(root->left,sum)+pathSum(root->right,sum);
}
private:
int getSum(TreeNode* root, int cur,int sum){
if(!root){
return 0;
}
cur=cur+root->val;
return (sum==cur)+getSum(root->left,cur,sum)+getSum(root->right,cur,sum);
}
};
Python实现
这道题分析的点是不一定是根节点,所以在遍历的时候需要注意左右分支得当成根节点递归的进行遍历,然后当前的根节点,也需要正常递归。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
if root is None:
return 0
return self.solve(root, 0, targetSum)+self.pathSum(root.left, targetSum)+self.pathSum(root.right, targetSum)
def solve(self, root, cur, target):
if root is None:
return 0
cur = cur+root.val
left = self.solve(root.left,cur,target)
right = self.solve(root.right, cur, target)
if cur==target:
cnt=1
else:
cnt = 0
return cnt+left+right
下面有一个不是很fancy的解决方案:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
res=0
def solve(self, root, cur, targetSum):
if not root:
return
if cur+root.val==targetSum:
self.res+=1
self.solve(root.left,cur+root.val, targetSum)
self.solve(root.right, cur+root.val, targetSum)
def pathSum(self, root: TreeNode, targetSum: int) -> int:
if not root:
return 0
self.solve(root,0,targetSum)
self.pathSum(root.left,targetSum)
self.pathSum(root.right,targetSum)
return self.res