1161. 最大层内元素和
思路:广度优先搜索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 f[10010];
int ct=1;
void dfs(TreeNode* root,int u){
if(root==nullptr) return ;
f[u]+=root->val;
ct=max(ct,u);
dfs(root->left,u+1);
dfs(root->right,u+1);
}
int maxLevelSum(TreeNode* root) {
memset(f,0,sizeof f);
dfs(root,1);
int mx=f[1];
int id=1;
for(int i=2;i<=ct;i++){
if(mx<f[i]){
mx=f[i];
id=i;
}
}
return id;
}
};