題目來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/path-sum-iii
給定一個二叉樹琳猫,它的每個結(jié)點都存放著一個整數(shù)值。
找出路徑和等于給定數(shù)值的路徑總數(shù)私痹。
路徑不需要從根節(jié)點開始脐嫂,也不需要在葉子節(jié)點結(jié)束,但是路徑方向必須是向下的(只能從父節(jié)點到子節(jié)點)紊遵。
二叉樹不超過1000個節(jié)點账千,且節(jié)點數(shù)值范圍是 [-1000000,1000000] 的整數(shù)。
示例:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
返回 3暗膜。和等于 8 的路徑有:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
遞歸解法:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int ans = 0;
public int pathSum(TreeNode root, int sum) {
if(root != null){
func(root,sum);
pathSum(root.left,sum);
pathSum(root.right,sum);
}
return ans;
}
private void func(TreeNode root, int sum){
if(root == null)
return;
if(root.val == sum)
ans++;
func(root.left,sum-root.val);
func(root.right,sum-root.val);
}
}