clueless coding // TODO: be smarter

LeetCode Nested List Weight Sum II: CPP Solution



TL;DR Code Solution


 *     // Constructor initializes an empty nested list.
 *     NestedInteger();
 *
 *     // Constructor initializes a single integer.
 *     NestedInteger(int value);
 *
 *     // Return true if this NestedInteger holds a single integer, rather than a nested list.
 *     bool isInteger() const;
 *
 *     // Return the single integer that this NestedInteger holds, if it holds a single integer
 *     // The result is undefined if this NestedInteger holds a nested list
 *     int getInteger() const;
 *
 *     // Set this NestedInteger to hold a single integer.
 *     void setInteger(int value);
 *
 *     // Set this NestedInteger to hold a nested list and adds a nested integer to it.
 *     void add(const NestedInteger &ni);
 *
 *     // Return the nested list that this NestedInteger holds, if it holds a nested list
 *     // The result is undefined if this NestedInteger holds a single integer
 *     const vector<NestedInteger> &getList() const;
 * };
 */
class Solution {
public:
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        int result = 0;
        int curr = 0;
        queue<vector<NestedInteger>> que;
        que.push(nestedList);

        while (!que.empty()) {
            int size = que.size();
            for (int i = 0; i < size; i++) {
                vector<NestedInteger> iter = que.front();
                que.pop();
                for (int j = 0; j < iter.size(); j++) {
                    if (iter[j].isInteger()) {
                        curr += iter[j].getInteger();
                    }
                    else {
                        que.push(iter[j].getList());
                    }
                }
            }
            result += curr;
        }

        return result;


    }