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

二叉树中和为某一值的路径

/*
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;
        if(root == NULL)
            return res;
        
        vector<int> path;
        int currentSum = 0;
        FindPath_(root,expectNumber,path,currentSum,res);
        return  res;
    }
    
    void FindPath_(TreeNode* root,int expectNumber,vector<int> &path,int currentNum,vector<vector<int>> &res){
        currentNum += root->val;
        path.push_back(root->val);
        
        bool isLeaf = root->left == NULL && root->right == NULL;
        if(currentNum == expectNumber && isLeaf){
            res.push_back(path);
        }
        
        if(root->left != NULL){
            FindPath_(root->left,expectNumber,path,currentNum,res);
        }
        if(root->right != NULL){
            FindPath_(root->right,expectNumber,path,currentNum,res);
        }
        
        currentNum -= root->val;
        path.pop_back();

    }
};

 

二叉树中和为某一值的路径