LeetCode 404 Sum of Left Leaves

LeetCode 404 Sum of Left Leaves

Topic link

Calculate the sum of all left leaves of a given binary tree.

Example:

   3
   / \
  9  20
    /  \
   15   7

In this binary tree, there are two left leaves, 9 and 15, so 24 is returned

Perform BFS on the binary tree. If the left child node of a node is a leaf node, add it to the answer. The AC code is as follows:

class Solution {
    
    
public:
    int sumOfLeftLeaves(TreeNode* root) {
    
    
        int ans=0;
        queue<TreeNode*>q;
        q.push(root);
        while(!q.empty()){
    
    
            TreeNode* t=q.front();
            q.pop();
            if(t){
    
    
                if(t->left){
    
    
                    q.push(t->left);
                    if(t->left->left==NULL&&t->left->right==NULL) ans+=t->left->val;
                }
                if(t->right) q.push(t->right);
            }
        }
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/qq_43765333/article/details/108676868