leetcode 437. Path Sum III

Posted ctqchina

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 437. Path Sum III相关的知识,希望对你有一定的参考价值。

样例:root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 7,一开始以为10 5 -3也算一种情况,但实际上是不算的。
/**
 * 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;
    int pos;
    
    int solve(TreeNode root, int sum){
        
        if(root == null) return 0;
        
        return (root.val == sum?1:0)+solve(root.left, sum-root.val)
            +solve(root.right, sum-root.val);
    }
    
    public int pathSum(TreeNode root, int sum) {
        
        if(root == null) return 0;
        
        return solve(root,sum)+pathSum(root.left,sum)+pathSum(root.right, sum);
    }
}

  

以上是关于leetcode 437. Path Sum III的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode:437. Path Sum III

leetcode 437. Path Sum III

LeetCode - 437. Path sum III

leetcode 437. Path Sum III

[Leetcode] Binary tree-- 437. Path Sum III

leetcode 437 路径和 Path Sum III