想不多寫函數,失敗了,(╯‵□′)╯︵┻━┻
Java,首先要有一個函數記錄某個點開始能找到符合累加和為sum的個數,然后在主函數中調用它并遞歸調用主函數,這里有很多遞歸
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int pathSum(TreeNode root, int sum) {
if(root==null) return 0;
else
return findPath(root,sum)+pathSum(root.left,sum)+pathSum(root.right,sum);
}
public int findPath(TreeNode root,int sum)
{
int res=0;
if(root==null) return res;
if(root.val==sum) res++;
res+=findPath(root.left,sum-root.val);
res+=findPath(root.right,sum-root.val);
return res;
}
}