leetcode-华为专题-129. 求根节点到叶节点数字之和

 

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> res;
    int sumNumbers(TreeNode* root) {

        if(root==NULL)
            return 0;
        dfs(root, 0);
        int tmp = 0;
        for(int i = 0; i < res.size(); i++){
            // cout<<i<<": "<<res[i]<<endl;
            tmp = tmp + res[i];
        }
        return tmp;
    }

    void dfs(TreeNode* root,int sum){
        if(root==NULL)
            return;
        if(root->left==NULL&&root->right==NULL){
            sum = sum*10 + root->val;
            res.push_back(sum);
            return;
        }
        sum = sum*10 + root->val;
        dfs(root->left, sum);
        dfs(root->right, sum);
        
    }
};

 

posted @ 2021-08-15 15:49  三一一一317  阅读(46)  评论(0)    收藏  举报