[LeetCode] 437. Path Sum III

来源:互联网 发布:php artisan 安装 编辑:程序博客网 时间:2024/06/05 10:31
You are given a binary tree in which each node contains an integer value.Find the number of paths that sum to a given value.The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8      10     /  \    5   -3   / \    \  3   2   11 / \   \3  -2   1Return 3\. The paths that sum to 8 are:1\.  5 -> 32\.  5 -> 2 -> 13\. -3 -> 11
class Solution {public:    int pathSum(TreeNode* root, int sum) {        stack<TreeNode *> stk;        int cnt = 0;        TreeNode *ptn = root;        while (!stk.empty() || ptn != nullptr) {            if (ptn != nullptr) {                stk.push(ptn);                ptn = ptn->left;            } else {                ptn = stk.top();                stk.pop();                cnt += __pathSum(ptn, sum);                ptn = ptn->right;            }        }        return cnt;    }private:    int __pathSum(TreeNode* root, int sum) {        if (root == nullptr) return 0;        int cnt = 0;        cnt += (root->val == sum);        cnt += __pathSum(root->left, sum - root->val);        cnt += __pathSum(root->right, sum - root->val);        return cnt;    }};

这里写图片描述

class Solution {public:    int pathSum(TreeNode* root, int sum) {        if (root == nullptr) return 0;        return SumUp(root, sum) + pathSum(root->left, sum) + pathSum(root->right, sum);    }private:    int SumUp(TreeNode* root, int sum) {        if (root == nullptr) return 0;        int cnt = 0;        cnt += root->val == sum;        cnt += SumUp(root->left, sum - root->val);        cnt += SumUp(root->right, sum - root->val);        return cnt;    }};

这里写图片描述