其他分享
首页 > 其他分享> > leetcode-华为专题-129. 求根节点到叶节点数字之和

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);
        
    }
};

 

标签:right,TreeNode,int,sum,节点,left,root,leetcode,求根
来源: https://www.cnblogs.com/ymec/p/15143607.html