404. Sum of Left Leaves

Posted 高数考了59

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了404. Sum of Left Leaves相关的知识,希望对你有一定的参考价值。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 static int wing=[]()
11 {
12     std::ios::sync_with_stdio(false);
13     cin.tie(NULL);
14     return 0;
15 }();
16 
17 class Solution 
18 {
19 public:
20     int sumOfLeftLeaves(TreeNode* root) 
21     {
22         if(root==NULL)
23             return 0;
24         queue<TreeNode*> q;
25         TreeNode *p=root;
26         q.push(p);
27         int count=0;
28         while(!q.empty())
29         {
30             p=q.front();
31             q.pop();
32             if(p->left!=NULL)
33             {
34                 q.push(p->left);
35                 if(p->left->left==NULL&&p->left->right==NULL)
36                     count+=p->left->val;
37             }
38             if(p->right!=NULL)
39                 q.push(p->right);
40         }
41         return count;
42     }
43 };

用层次遍历,左节点进队列时判定是否为叶节点,若是,则加计数器。

以上是关于404. Sum of Left Leaves的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-404. Sum of Left Leaves

404. Sum of Left Leaves

Leetcode 404. Sum of Left Leaves

404. Sum of Left Leaves

404. Sum of Left Leaves

404. Sum of Left Leaves