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

[leetcode] Path sum路径之和

时间:2014-05-07 10:15:46      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   color   

要求
给定树,与路径和,判断是否存在从跟到叶子之和为给定值的路径。比如下图中,给定路径之和为22,存在路径<5,4,11,2>,因此返回true;否则返回false.
5 / 4 8 / / 11 13 4 / \ 7 2 5
思路
递归,从跟到叶子判断,如果在叶子处剩下的给定值恰好为给定值,那么返回ture.
参考代码
bubuko.com,布布扣
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) {
        if (root == NULL)
            return false;
        if (root->left == NULL && root->right == NULL && root->val == sum)
            return true;
        if (root->left != NULL && hasPathSum(root->left, sum - root->val))
            return true;
        if (root->right != NULL && hasPathSum(root->right, sum - root->val))
            return true;
        return false;
    }
};
bubuko.com,布布扣

 

扩展

求出所有符合条件的路径。例如,上题中返回<<5, 4, 11, 2>, <5, 8, 4, 5>>

参考代码

bubuko.com,布布扣
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public: 
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        vector<vector<int> > res;
        vector<int> tmp;
        if (root == NULL)
            return res;
        tmp.push_back(root->val);
        pathSumRecur(root, sum, tmp, res);
        return res;
    }
    void pathSumRecur(TreeNode *root, int sum , vector<int> &tmp, vector<vector<int> > &res)
    {
        if (root == NULL)
            return;
        if (root->left == NULL && root->right == NULL && root->val == sum)
        {
            res.push_back(tmp);
        }
        if(root->left != NULL)
        {
            tmp.push_back(root->left->val);
            pathSumRecur(root->left, sum - root->val, tmp, res);
            tmp.pop_back();
        }
        if(root->right != NULL)
        {
            tmp.push_back(root->right->val);
            pathSumRecur(root->right, sum - root->val, tmp, res);
            tmp.pop_back();
        }
    }
};
bubuko.com,布布扣

 

[leetcode] Path sum路径之和,布布扣,bubuko.com

[leetcode] Path sum路径之和

标签:style   blog   class   code   java   color   

原文地址:http://www.cnblogs.com/kaituorensheng/p/3710308.html

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