题目描述
示例
思路
本题是对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 level_sum[10005];
int max_level = 0;
public:
void dfs(TreeNode* x, int d){
max_level = max(max_level, d);
level_sum[d] += x->val;
if(x->left!=nullptr) dfs(x->left, d+1);
if(x->right!=nullptr) dfs(x->right, d+1);
}
int maxLevelSum(TreeNode* root) {
dfs(root, 1);
int sum=1<<31, ans=0;
for(int i=1;i<=max_level;i++){
if(level_sum[i]>sum){
sum = level_sum[i];
ans = i;
}
}
return ans;
}
};