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

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...
win11本地账户怎么改名?win11很多操作都变了样,用户如果想要...