BFS实现:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int deepestLeavesSum(TreeNode* root) {
queue<TreeNode *> queue;
queue.push(root);
int sum;
while(!queue.empty())
{
sum = 0;
int size = queue.size();
for(int i = 0;i< size;i++)
{
TreeNode* curr = queue.front();
queue.pop();
sum += curr->val;
if(curr->left) queue.push(curr->left);
if(curr->right) queue.push(curr->right);
}
}
return sum;
}
};
DFS实现:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int deepestLeavesSum(TreeNode* root) {
if(root == nullptr)
return 0;
dfs(root,1);
return sum;
}
private:
void dfs(TreeNode* root,int cur_depth) {
if(root == nullptr) return;
if(max_depth < cur_depth)
{
sum = root->val;
max_depth = cur_depth;
}else if(max_depth == cur_depth){
sum += root->val;
}
dfs(root->left,cur_depth + 1);
dfs(root->right,cur_depth + 1);
}
int sum = 0;
int max_depth = 1;
};
这道题目,BFS要比DFS更好理解和实现,使用DFS时要存储当前最大深度。如果遇到更大深度时清空sum。这里使用了类成员变量sum和max_depth,当成全局变量使用。