C++ BFS solution


  • 0
    T

    class Solution {
    public:
    int sumOfLeftLeaves(TreeNode* root) {
    if(!root) return 0;
    if(!root->left && !root->right) return 0;
    queue<TreeNode*> myQueue;
    myQueue.push(root);
    int sum = 0;
    while(!myQueue.empty())
    {
    int size = myQueue.size();
    for(int i = 0; i< size; ++i)
    {
    TreeNode* temp = myQueue.front();
    myQueue.pop();

                if(temp->left)
                {
                    myQueue.push(temp->left);
                    if(!temp->left->left && !temp->left->right)
                        sum += temp->left->val;
                }
                if(temp->right) myQueue.push(temp->right);
                
            }
        }
        return sum;
    }
    

    };


Log in to reply
 

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