微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

LeetCode 437. Path Sum III

https://leetcode.com/problems/path-sum-iii/

本题和之前的Path Sum有些类似,但需要注意的是,之前的路径必须是从根节点到叶子节点的路径和,而本题中任意路径都需要统计,所以我们在递归的每一层中,向下递归时需要考虑包含当前节点和不包含当前节点的情况。代码如下:

/**
 * DeFinition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    
    //以Node为根节点的二叉树中,寻找包含Node 的路径
    int findpath(TreeNode* node ,int num){
        if( node == nullptr )
            return 0;
        int res = 0;
        if( node->val == num )
            res += 1;    
        res += findpath( node->left, num - node->val );
        res += findpath( node->right, num - node->val );    
        return res;
    }
    
    
    int pathSum(TreeNode* root, int sum) {
        if( root == nullptr )
            return 0;
        int res = findpath( root,sum );
        
        res += pathSum( root->left, sum );
        res += pathSum( root->right, sum );
        
        return res;
        
    }
};

原文地址:https://cloud.tencent.com/developer/article/2028501

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐