Path Sum II/III

方法:递归的方式,这里使用一个变量记录cur保存遍历过程中的变量,类似于前序遍历

/**
 * 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:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> result;
        
        vector<int> cur;
        pathSum(root, sum, cur, result);
        return result;
    }
    
    void pathSum(TreeNode *root, int gap, vector<int> &cur, vector<vector<int>> &result)
    {
        if(root == nullptr)
            return;
        
        cur.push_back(root->val);
        if(root->left == nullptr && root->right == nullptr && root->val == gap)
            result.push_back(cur);
            
        pathSum(root->left, gap - root->val, cur, result);
        pathSum(root->right, gap - root->val, cur, result);
        
        cur.pop_back();
    }
};

 同样,对应path sum III问题,使用前序遍历的方式

posted @ 2017-04-18 21:19  chengcy  Views(140)  Comments(0)    收藏  举报