Efficient and Elegant. 3 ms recursive. C++


  • 0
    P

    This should be as fast as iterative. The feature is down right now, so I cannot check.

    class Solution {
    public:
    
        int dfs(auto &root, int sum)
        {  
            if(!root -> left && !root -> right) return sum * 10 + root -> val;
            if(root -> left && root -> right)
                return dfs(root -> left, sum * 10 + root -> val)
                    + dfs(root -> right, sum * 10 + root -> val);
            if(!root -> left) return dfs(root -> right, sum * 10 + root -> val);
            if(!root -> right) return dfs(root -> left, sum * 10 + root -> val);
            return 0;
        }
        
        int sumNumbers(TreeNode* root) {
            if(!root) return 0;
            return dfs(root, 0);
        }
    };
    

    A bit verbose.


Log in to reply
 

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