首页 > 代码库 > [leetcode] Path sum路径之和

[leetcode] Path sum路径之和

要求
给定树,与路径和,判断是否存在从跟到叶子之和为给定值的路径。比如下图中,给定路径之和为22,存在路径<5,4,11,2>,因此返回true;否则返回false.
5 / 4 8 / / 11 13 4 / \ 7 2 5
思路
递归,从跟到叶子判断,如果在叶子处剩下的给定值恰好为给定值,那么返回ture.
参考代码
/**
 * 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;
    }
};

 

扩展

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

参考代码

/**
 * 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();
        }
    }
};