1302. Deepest Leaves Sum**
https://leetcode.com/problems/deepest-leaves-sum/
题目描述
Given a binary tree, return the sum of values of its deepest leaves.
Example 1:
![](https://i-blog.csdnimg.cn/blog_migrate/3079d1e9b128e78ef52624caf788795e.png)
Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15
Constraints:
- The number of nodes in the tree is between
1
and10^4
. - The value of nodes is between
1
and100
.
C++ 实现 1
使用递归还是有点麻烦, 发现用迭代更为方便, 使用层序遍历. 使用 sum
将每一层的叶子节点进行加和. 如果进入到新的一层, 那么 sum 要先进行清零操作.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int deepestLeavesSum(TreeNode* root) {
if (!root) return 0;
queue<TreeNode*> q;
q.push(root);
int sum = 0;
while (!q.empty()) {
auto size = q.size();
// 当进入新的 level, sum 清零
sum = 0;
while (size --) {
auto r = q.front();
q.pop();
if (r->left) q.push(r->left);
if (r->right) q.push(r->right);
if (!r->left && !r->right) sum += r->val;
}
}
return sum;
}
};
C++ 实现 2
(20210312 更新) 这题也可以用递归来做: 思路是使用 max_depth
记录最大的深度, 用 depth
记录当前的深度. 那么如果访问到某节点, 其 depth
大于 max_depth
时, 说明目前该节点是更深的, 因此要更新 max_depth
, 累加和 sum
此时要清零. 之后如果再遇到深度等于 max_depth
的节点, 就将其值加入到 sum
中.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
int max_depth = 0, sum = 0;
void dfs(TreeNode *root, int depth) {
if (!root) return;
if (depth > max_depth) {
max_depth = depth;
sum = 0;
}
if (depth == max_depth) sum += root->val;
dfs(root->left, depth + 1);
dfs(root->right, depth + 1);
}
public:
int deepestLeavesSum(TreeNode* root) {
dfs(root, 0);
return sum;
}
};