Clean C++ Deque based Solution


  • 0
    F
    class Solution {
    public:
        int sumNumbers(TreeNode* root) {
            if (!root) return 0;
            int sum = 0;
            TreeNode* cur;
            deque<TreeNode*> dq;
            dq.push_back(root);
            while (!dq.empty()) {
                cur = dq.front();
                dq.pop_front();
                if (cur->right) {
                    cur->right->val += cur->val * 10;
                    dq.push_back(cur->right);
                }
                if (cur->left) {
                    cur->left->val += cur->val * 10;
                    dq.push_back(cur->left);
                }
                if (!cur->left && !cur->right) {
                    sum += cur->val;
                }
            }
            return sum;
        }
    };

Log in to reply
 

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