求二叉树的所有路径,使用先根遍历,递归结束条件为到达叶子节点,同时还要分别递归左子树和右子树之后加入回溯。

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */
#include<numeric>
class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    void dfs(TreeNode* root,vector<string>& result,string& path){
        path.push_back(root->val + 48);
        if(root!=nullptr && root->left==nullptr && root->right==nullptr){
            result.push_back(path);
            return;
        }
        if(root->left){
            dfs(root->left,result,path);
            path.pop_back();
        }
        if(root->right){
            dfs(root->right,result,path);
            path.pop_back();
        }
    }
    
    int sumNumbers(TreeNode* root) {
        if(root==nullptr) return 0;
        vector<string> result;
        string path;
        dfs(root,result,path);
        vector<int> vec{};
        for(auto str: result){
            stringstream s_stream{};
            s_stream<<str;
            int temp{};
            s_stream>>temp;
            vec.push_back(temp);
        }
        int sum=0;
        for(auto x: vec) sum+=x;
        return sum;
    }
};