Need help with my code


  • 0
    R

    I can't figure out what's wrong with my code. I'm getting random integer output with the "{ }" input. I suspect it's some uninitialized value but I can't figure it out.

    Thanks

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        struct Entry {
            Entry(TreeNode* n, int prev) : node(n), prev_sum(prev) {}
            TreeNode* node;  
            int prev_sum;
        };
        
        int sumNumbers(TreeNode *root) {
            vector<Entry> entries;
            entries.emplace_back(root, 0);
            int total_sum = 0;
            while (!entries.empty()) {
                Entry current = entries.back();
                entries.pop_back();
                if (current.node == NULL) {
                    total_sum += current.prev_sum;
                } else {
                    int current_sum = current.prev_sum + current.node->val;
                    entries.emplace_back(current.node->left, current_sum);
                    entries.emplace_back(current.node->right, current_sum);
                }
            }
        }
    };

Log in to reply
 

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