LeetCode 1302 层数最深叶子节点的和[BFS DFS] HERODING的LeetCode之路
Posted HERODING23
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 1302 层数最深叶子节点的和[BFS DFS] HERODING的LeetCode之路相关的知识,希望对你有一定的参考价值。
解题思路:
对于二叉树中某一层节点的操作,DFS和BFS都可以轻松解决,DFS只要在递归时加入层次到达目的层进行累加即可,DFS就一层一层进行,直到最后一层,首先是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
private:
int sum = 0;
int depth = 0;
public:
int deepestLeavesSum(TreeNode* root)
dfs(root, 0);
return sum;
void dfs(TreeNode* node, int layer)
if(node == nullptr)
return;
if(layer > depth)
sum = node->val;
depth = layer;
else if(layer == depth)
sum += node->val;
dfs(node->left, layer + 1);
dfs(node->right, layer + 1);
;
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)
int sum;
queue<TreeNode*> q;
q.emplace(root);
while(!q.empty())
int n = q.size();
sum = 0;
for(int i = 0; i < n; i ++)
TreeNode* node = q.front();
sum += node->val;
q.pop();
if(node->left != nullptr)
q.emplace(node->left);
if(node->right != nullptr)
q.emplace(node->right);
return sum;
;
以上是关于LeetCode 1302 层数最深叶子节点的和[BFS DFS] HERODING的LeetCode之路的主要内容,如果未能解决你的问题,请参考以下文章