
想不多写函数,失败了,(╯‵□′)╯︵┻━┻
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;
}
}
网友评论