30 Day Challenge Day 2 | Leetcode 1302. Deepest Leaves Sum
题解
非常典型的二叉树遍历的题,BFS做起来更顺手一些,DFS处理起来要稍稍注意些。
BFS
class Solution {
public:
int deepestLeavesSum(TreeNode* root) {
if(!root) return 0;
queue<TreeNode*> q;
q.push(root);
int sum = 0;
while(!q.empty()) {
int sz = q.size();
sum = 0;
for(int i = 0; i < sz; i++) {
TreeNode* t = q.front();
q.pop();
sum += t->val;
if(t->left) {
q.push(t->left);
}
if(t->right) {
q.push(t->right);
}
}
}
return sum;
}
};
DFS
class Solution {
public:
int deepestLeavesSum(TreeNode* root) {
int level = 0, deepest = 0, sum = 0;
deepestSum(root, level, deepest, sum);
return sum;
}
void deepestSum(TreeNode* node, int level, int &deepest, int &sum) {
if(!node) return;
level += 1;
if(level == deepest) {
sum += node->val;
} else if (level > deepest) {
sum = node->val;
deepest = level;
}
deepestSum(node->left, level, deepest, sum);
deepestSum(node->right, level, deepest, sum);
}
};