码迷,mamicode.com
首页 > 其他好文 > 详细

404. Sum of Left Leaves

时间:2018-05-26 20:28:35      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:def   static   win   treenode   lse   ret   stat   root   count   

 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

标签:def   static   win   treenode   lse   ret   stat   root   count   

原文地址:https://www.cnblogs.com/zhuangbijingdeboke/p/9094086.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!