首页 > 代码库 > 剑指offer---二叉树中和为某一值的路径

剑指offer---二叉树中和为某一值的路径

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
class Solution {
public:
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        vector<vector<int> >res;
        vector<int> cur;
        path(root,expectNumber,res,cur);
        return res;
    }
     void path(TreeNode *root,int sum, vector<vector<int> >&res,vector<int> &cur)
     {
        if(root==NULL)
            return ;
        cur.push_back(root->val);
        if(root->left==NULL&&root->right==NULL)
            {
            if(sum==root->val)
                res.push_back(cur);
        }
        if(root->left)
        path(root->left,sum-root->val,res,cur);
        if(root->right)
        path(root->right,sum-root->val,res,cur);
        cur.pop_back();
    }
};

 

剑指offer---二叉树中和为某一值的路径