leetcode 404. Sum of left leaves

Computes 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 return to 24 

ideas:
  the layer traverses a tree, finds the left leaf, and sums it
 1 #include<queue>
 2 class Solution {
 3 public:
 4     int sumOfLeftLeaves(TreeNode* root) {
 5         queue<TreeNode*> q;
 6         q.push(root);
 7         int sum = 0;
 8         while(!q.empty()){
 9             TreeNode* temp = q.front();
10             q.pop();
11             if(temp == NULL) break;
12             if(temp->left) {
13                 q.push(temp->left);
14                 if(temp->left->left == NULL && temp->left->right == NULL) sum += temp->left->val;
15             }
16             if(temp->right) q.push(temp->right);
17         }
18         return sum;
19     }
20 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325043984&siteId=291194637