当前位置: 代码迷 >> 综合 >> Leetcode 1161. 最大层内元素和(DAY 10)
  详细解决方案

Leetcode 1161. 最大层内元素和(DAY 10)

热度:29   发布时间:2023-11-17 20:34:21.0

原题题目

在这里插入图片描述



代码实现(首刷自解)

/*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*/#define MAX 10001
#define MIN -9999999999int maxLevelSum(struct TreeNode* root){
    int maxsum = MIN,tempsum,size,top = -1,rear = -1,level = 1,maxlevel = 0;struct TreeNode* queue[MAX];struct TreeNode* position;queue[++rear] = root;while(rear != top){
    size = rear - top;tempsum = 0;while(size--){
    position = queue[++top];tempsum += position->val;if(tempsum > maxsum && !size){
    maxlevel = level;maxsum = tempsum;}if(position->left)queue[++rear] = position->left;if(position->right)queue[++rear] = position->right;}level++;}return maxlevel;
}