码迷,mamicode.com
首页 > 其他好文 > 详细

letecode [437] - Path Sum III

时间:2019-06-26 15:06:06      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:用户   info   example   ini   差值   ack   roo   res   parent   

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   1

Return 3. The paths that sum to 8 are:

1.  5 -> 3
2.  5 -> 2 -> 1
3. -3 -> 11

题目大意

  给定二叉树,求路径之和满足目标值的路径数量。不要求从根节点开始,也不要求到叶节点为止。即路径可以为任意一段路径,但必须从上往下。

理  解:

  根据题意,在每一层它满足条件的情况都与上一层都关。对于第一层,和目标值作比较即可。第二层,需要和目标值作比较或者与目标值-第一层差值作比较。

  后面的层一次类推,直接和目标值比较或者与目标值-上一层余值的差值比较。因为每一层都可能是路径起始节点。

  使用vector保存上一层余值和目标值,若当前层值等于余值或目标值,则找到一个路径。同时,需要减去当前层的值更新vector中的值以便下一层计算。

代 码 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 countPath(TreeNode* root, int sum,vector<int> vec){
        if(root==NULL) return 0;
        int count = 0;
        vec.push_back(sum);
        for(int i=0;i<vec.size();++i){
            if(vec[i]==root->val)
                count++;
            vec[i] -= root->val;
        }
        count += countPath(root->left,sum,vec) + countPath(root->right,sum,vec);
        return count;
    }
    
    int pathSum(TreeNode* root, int sum) {
        if(root==NULL) return 0;
        int count = 0;
        vector<int> vec;
        count += countPath(root,sum,vec);
        return count;
    }
};

运行结果:

  执行用时 :72 ms, 在所有 C++ 提交中击败了8.21%的用户

  内存消耗 :63.2 MB, 在所有 C++ 提交中击败了5.29%的用户

letecode [437] - Path Sum III

标签:用户   info   example   ini   差值   ack   roo   res   parent   

原文地址:https://www.cnblogs.com/lpomeloz/p/11089879.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!