437. Path Sum III

想不多寫函數,失敗了,(╯‵□′)╯︵┻━┻

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;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容