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 };

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

转载于:https://www.cnblogs.com/zhuangbijingdeboke/p/9094086.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值