C++ 5ms DFS code, easy to understand


  • 4
    A

    class Solution {
    public:
    int sumNumbers(TreeNode *root) {
    return traverse(0, root);
    }

    int traverse(int fathers, TreeNode *root) {
        if (root == NULL) {
            return 0;
        }
        
        int cur = fathers * 10 + root->val;
        
        int sum = traverse(cur, root->left) + traverse(cur, root->right);
        
        return (sum != 0) ? sum : cur;
    }
    

    };


Log in to reply
 

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