[力扣c++实现] 437. 路径总和 III

437. 路径总和 III

给定一个二叉树的根节点 root ,和一个整数 targetSum ,求该二叉树里节点值之和等于 targetSum 的 路径 的数目。

路径 不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/path-sum-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

示例 1:
在这里插入图片描述

输入:root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
输出:3
解释:和等于 8 的路径有 3 条,如图所示。

示例 2:

输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:3

提示:

二叉树的节点个数的范围是 [0,1000]
-109 <= Node.val <= 109
-1000 <= targetSum <= 1000

#include <stack>
#include <algorithm>
#include <iostream>

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

typedef struct TreeNode Node;

class Solution {
public:
    void traverseAndCount(TreeNode* root,long& targetSum,int& count)
    {
        if (!root)
            return;
        targetSum -= root->val;
        if (targetSum == 0)
            count+=1;
        if (root->left)
        {
            traverseAndCount(root->left,targetSum,count);
            targetSum += root->left->val;
        }

        if (root->right)
        {
            traverseAndCount(root->right,targetSum,count);
            targetSum += root->right->val;
        }
    }

    void getAllNode(std::stack<TreeNode*>& nodeStack,TreeNode* root)
    {
        if (root)
        {
            nodeStack.push(root);
            getAllNode(nodeStack,root->left);
            getAllNode(nodeStack,root->right);
        }
    }

    int pathSum(TreeNode* root, int targetSum) {
        std::stack<TreeNode*> nodeStack;
        getAllNode(nodeStack,root);
        int count = 0;
        while (!nodeStack.empty())
        {
            auto node = nodeStack.top();
            long increVal = targetSum;
            traverseAndCount(node,increVal,count);
            nodeStack.pop();
        }
        return count;
    }
};

int main()
{
    Solution slu;
    Node root(3);
    Node node1(2);
    Node node2(3);
    Node node3(3);
    Node node4(1);
 
    root.left = &node1;
    root.right= &node2;
    node1.right = &node3;
    node2.right = &node4;
    
    std::cout << slu.pathSum(&root,5) << std::endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值