美文网首页
437. Path Sum III

437. Path Sum III

作者: hyhchaos | 来源:发表于2016-12-05 22:38 被阅读44次

想不多写函数,失败了,(╯‵□′)╯︵┻━┻

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;
    }
}

相关文章

网友评论

      本文标题:437. Path Sum III

      本文链接:https://www.haomeiwen.com/subject/kdelmttx.html