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

输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

思路:dfs

    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        vector<vector<int> >res;
        vector<int> path;
        if(root==NULL||expectNumber==0) return res;
        Find(root,expectNumber,res,path);
        return res;
    }
    void Find(TreeNode*root,int expect,vector<vector<int> >&res,vector<int>&path)
    {
        
        path.push_back(root->val);
        if(root->left==NULL&&root->right==NULL)
        {
            int temp_pathSum=0;
            for(int i=0;i<path.size();i++)
            {
                temp_pathSum+=path[i];
            }
            if(temp_pathSum==expect)
            {
                res.push_back(path);
            }
        }
        
        if(root->left!=NULL)
            Find(root->left,expect,res,path);
        if(root->right!=NULL)
            Find(root->right,expect,res,path);
        path.pop_back();
    }

原文地址:https://www.cnblogs.com/trouble-easy/p/12966903.html