Leetcode 129

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode* root) {
        if(root == NULL) return 0;
        int res = 0;
        DFS(root,res,0);
        return res;
    }
    
    void DFS(TreeNode* root,int &res,int add){
        if(root->left == NULL && root->right == NULL){
            add = add*10 + root->val;
            res += add;
            return;
        }
        add = add*10 + root->val;
        if(root->left != NULL){
            DFS(root->left,res,add);
        }
        if(root->right != NULL){
            DFS(root->right,res,add);
        }
    }
};

EZ

猜你喜欢

转载自www.cnblogs.com/cunyusup/p/10534584.html
129
今日推荐