My C++ DFS solution


  • 1
    T
    class Solution {
    public:
        int sumNumbers(TreeNode *root) {
            map<TreeNode*, int> m;
            int sum = 0;
            stack<TreeNode*> s;
            if(root != NULL) {
                m[root] = root->val;
                s.push(root);
            }
            while(!s.empty()) {
                TreeNode* t = s.top();
                s.pop();
                if(t->left != NULL) {
                    m[t->left] = 10*m[t] + t->left->val;
                    s.push(t->left);
                } 
                if(t->right != NULL) {
                    m[t->right] = 10*m[t] + t->right->val;
                    s.push(t->right);
                }
                if(t->left == NULL && t->right == NULL) {
                    sum += m[t];
                }
                
            }
            return sum;
            
        }
    };

Log in to reply
 

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