LeetCode 1161. 最大层内元素和

tech2025-11-05  6

原题目:https://leetcode-cn.com/problems/maximum-level-sum-of-a-binary-tree/

 

思路:

使用BFS,记录每一层的值之和,返回最大的层即可

 

代码:

class Solution { public: int maxLevelSum(TreeNode* root) { int maxlen=INT_MIN,ans,index=1; queue<TreeNode*> q; q.push(root); TreeNode* tmp; while(!q.empty()){ int t = 0; int size = q.size(); for(int i=0;i<size;i++){ tmp = q.front();q.pop(); t += tmp->val; if(tmp->left) q.push(tmp->left); if(tmp->right)q.push(tmp->right); } if(t>maxlen){ maxlen = t;ans=index; } index++; } return ans; } };

 

最新回复(0)