C++ BFS Solution with a Boolean in a queue


  • 0
    W
    class Solution {
    public:
        int sumOfLeftLeaves(TreeNode* root) {
            if(!root)   return 0;
            int sum = 0;
            queue<pair<TreeNode*, bool>> q;
            q.push(make_pair(root,false));
            while(!q.empty()) {
                auto cur = q.front();
                q.pop();
                if(cur.first->left)
                    q.push(make_pair(cur.first->left, true));
                if(cur.first->right)
                    q.push(make_pair(cur.first->right, false));
                if(!cur.first->left && !cur.first->right && cur.second)
                    sum += cur.first->val;
            }
            
            return sum;
        }
    };
    
    

Log in to reply
 

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