C++ Only 3 line and 8ms for my code


  • 5
    Z

    class Solution {

    public:

    int sumNumbers(TreeNode *root) {
    
        if (!root) return 0;
    
        if (!root->left && !root->right) return root->val;
    
        return (root->left ? root->left->val += root->val * 10, sumNumbers(root->left) : 0) + (root->right ? root->right->val += root->val * 10, sumNumbers(root->right) : 0);
    
    } 
    

    };


  • 0
    S

    Well, you can actually use the same style of the third line to refactor the code, then it can be only one line...


  • 2
    M

    You may change the tree when you do this!!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.