现在的位置: 首页 > 综合 > 正文

Path Sum II

2017年12月18日 ⁄ 综合 ⁄ 共 510字 ⁄ 字号 评论关闭

利用递归处理

/**
 * 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> >ans;
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        vector<int>v;
        Sum(root,sum,v);
        return ans;
    }
    void Sum(TreeNode *root, int sum, vector<int>res){
      if(root == NULL) return ;
      res.push_back(root->val);
      if(root->val == sum && root->left == NULL && root->right == NULL)
        ans.push_back(res);
       Sum(root->left,sum-root->val,res);
       Sum(root->right,sum-root->val,res);
    }
};

抱歉!评论已关闭.