437 Path Sum III 路径总和 III

给定一个二叉树,二叉树的每个节点含有一个整数。
找出路径和等于给定数的路径总数。
路径不需要从根节点开始,也不需要在叶节点结束,当路径方向必须是向下的(只从父节点到子节点)。
二叉树不超过1000个节点,节点的整数值的范围是[-1000000,1000000]。
示例:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
      10
     / 
    5   -3
   /    
  3   2   11
 /   
3  -2   1
返回 3. 和等于8的路径有:
1.  5 -> 3
2.  5 -> 2 -> 1
3. -3 -> 11
详见:https://leetcode.com/problems/path-sum-iii/description/
C++:

方法一:

/**
 * 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:
    int pathSum(TreeNode* root, int sum) {
        if(root==nullptr)
        {
            return 0;
        }
        return helper(root,sum)+pathSum(root->left,sum)+pathSum(root->right,sum);
    }
    int helper(TreeNode *root,int sum)
    {
        int res=0;
        if(root==nullptr)
        {
            return res;
        }
        if(sum==root->val)
        {
            ++res;
        }
        res+=helper(root->left,sum-root->val);
        res+=helper(root->right,sum-root->val);
        return res;
    }
};

方法二:

/**
 * 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:
    int pathSum(TreeNode* root, int sum) {
        int res=0;
        vector<TreeNode*> out;
        helper(root,sum,0,out,res);
        return res;
    }
    void helper(TreeNode* node,int sum,int curSum,vector<TreeNode*> &out,int &res)
    {
        if(!node)
        {
            return;
        }
        out.push_back(node);
        curSum+=node->val;
        if(curSum==sum)
        {
            ++res;
        }
        int t=curSum;
        for(int i=0;i<out.size()-1;++i)
        {
            t-=out[i]->val;
            if(t==sum)
            {
                ++res;
            }
        }
        helper(node->left,sum,curSum,out,res);
        helper(node->right,sum,curSum,out,res);
        out.pop_back();
    }
};

 参考:https://www.cnblogs.com/grandyang/p/6007336.html

原文地址:https://www.cnblogs.com/xidian2014/p/8892806.html