LeetCode //C - 1161. Maximum Level Sum of a Binary Tree

这篇具有很好参考价值的文章主要介绍了LeetCode //C - 1161. Maximum Level Sum of a Binary Tree。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1161. Maximum Level Sum of a Binary Tree

Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.

Return the smallest level x such that the sum of all the values of nodes at level x is maximal.
 

Example 1:

LeetCode //C - 1161. Maximum Level Sum of a Binary Tree,LeetCode,leetcode,c语言,算法

Input: root = [1,7,0,7,-8,null,null]
Output: 2
**Explanation: **
Level 1 sum = 1.
Level 2 sum = 7 + 0 = 7.
Level 3 sum = 7 + -8 = -1.
So we return the level with the maximum sum which is level 2.

Example 2:

Input: root = [989,null,10250,98693,-89388,null,null,null,-32127]
Output: 2

Constraints:
  • The number of nodes in the tree is in the range [ 1 , 1 0 4 ] [1, 10^4] [1,104].
  • − 1 0 5 < = N o d e . v a l < = 1 0 5 -10^5 <= Node.val <= 10^5 105<=Node.val<=105

From: LeetCode
Link: 1161. Maximum Level Sum of a Binary Tree文章来源地址https://www.toymoban.com/news/detail-816448.html


Solution:

Ideas:
  1. Initial Setup:
  • A dynamic queue is created to keep track of nodes to visit next. This queue will store pointers to each node in the binary tree.
  • The variables maxSum and maxLevel are initialized to store the maximum sum encountered and the corresponding level number. Initially, maxSum is set to the value of the root node, and maxLevel is set to 1.
  1. Enqueue Root Node:
  • The root node is enqueued followed by a NULL marker. This NULL marker is used to identify when all nodes at a particular level have been processed, and it’s time to move to the next level.
  1. Traversal Loop:
  • The loop continues until there are no more nodes left to process in the queue.
  • It dequeues nodes one by one and sums their values.
  • When a NULL marker is dequeued, it means the end of the current level is reached:
    • If the sum of the current level is greater than maxSum, update maxSum and maxLevel with the current sum and level number.
    • Reset the currentSum to zero for the next level’s sum.
    • Increment the level count, and if there are more nodes to process, enqueue another NULL marker to indicate the end of the next level.
  1. Child Nodes:
  • For each non-NULL node dequeued, the function enqueues its child nodes (left and then right) if they exist.
  • The queue size is checked and dynamically expanded if necessary by using realloc.
  1. Return Maximum Level:
  • After the traversal is complete, the function returns the maxLevel, which corresponds to the level with the maximum sum.
  1. Memory Management:
  • Before exiting the function, the dynamically allocated memory for the queue is freed to prevent memory leaks.
Code:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int maxLevelSum(struct TreeNode* root) {
    if (root == NULL) return 1;

    // Dynamically allocate a queue to hold pointers to TreeNodes
    int queueSize = 1024; // initial size
    struct TreeNode** queue = (struct TreeNode**)malloc(queueSize * sizeof(struct TreeNode*));
    if (!queue) return -1; // allocation failed

    int front = 0, rear = 0, level = 1, maxSum = root->val, maxLevel = 1, currentSum = 0;

    // Enqueue the root and a NULL marker for level 1
    queue[rear++] = root;
    queue[rear++] = NULL;

    while (front < rear) {
        struct TreeNode* node = queue[front++];

        if (node == NULL) {
            if (currentSum > maxSum) {
                maxSum = currentSum;
                maxLevel = level;
            }
            // Reset current sum for next level
            currentSum = 0;
            // Increase level number
            level++;
            // Continue only if there are more nodes to process
            if (front < rear) {
                queue[rear++] = NULL; // Marker for the next level
            }
        } else {
            // Add the node's value to the current level sum
            currentSum += node->val;

            // Enqueue child nodes
            if (node->left) {
                if (rear >= queueSize) {
                    // Increase queue size
                    queueSize *= 2;
                    queue = (struct TreeNode**)realloc(queue, queueSize * sizeof(struct TreeNode*));
                    if (!queue) return -1; // reallocation failed
                }
                queue[rear++] = node->left;
            }
            if (node->right) {
                if (rear >= queueSize) {
                    // Increase queue size
                    queueSize *= 2;
                    queue = (struct TreeNode**)realloc(queue, queueSize * sizeof(struct TreeNode*));
                    if (!queue) return -1; // reallocation failed
                }
                queue[rear++] = node->right;
            }
        }
    }

    free(queue); // Free the queue
    return maxLevel;
}

到了这里,关于LeetCode //C - 1161. Maximum Level Sum of a Binary Tree的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Leetcode 3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K

    Leetcode 3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K 1. 解题思路 2. 代码实现 题目链接:3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K 这一题我的思路上就是一个二分的思路,先确定一个上下界,然后不断通过二分来找到最大的price不超过k的值。 因此,剩下的

    2024年01月20日
    浏览(43)
  • LeetCode //C - 918. Maximum Sum Circular Subarray

    Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums. A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n]. A subarray may only include each element

    2024年02月07日
    浏览(46)
  • LeetCode 918. Maximum Sum Circular Subarray【数组,动态规划】中等

    本文属于「征服LeetCode」系列文章之一,这一系列正式开始于2021/08/12。由于LeetCode上部分题目有锁,本系列将至少持续到刷完所有无锁题之日为止;由于LeetCode还在不断地创建新题,本系列的终止日期可能是永远。在这一系列刷题文章中,我不仅会讲解多种解题思路及其优化,

    2024年02月15日
    浏览(49)
  • 【算法】Maximum Sum of Two Non-Overlapping Subarrays 两个非重叠子数组的最大和

    问题 有一个整数数组nums,和2个整数firstlen,secondlen,要求找出2个非重叠子数组中的元素的最大和,长度分别是firstlen,secondlen。 不限制2个子数组的先后顺序。 firstlen,secondlen的范围 [ 1 , 1000 ] [1,1000] [ 1 , 1000 ] firstlen+secondlen的范围 [ 2 , 1000 ] [2,1000] [ 2 , 1000 ] f i r s t l e n ,

    2023年04月27日
    浏览(106)
  • LintCode 650 · Find Leaves of Binary Tree (binary tree 后序遍历非常好的题目!)

    650 · Find Leaves of Binary Tree Algorithms Medium Description Given a binary tree, collect a tree’s nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty. Example Example1 Input: {1,2,3,4,5} Output: [[4, 5, 3], [2], [1]]. Explanation: / 2 3 / 4 5 Example2 Input: {1,2,3,4} Output: [[4, 3], [2], [1]]. Explanation:

    2024年02月20日
    浏览(38)
  • PAT 1174 Left-View of Binary Tree 题干不知所云

    个人学习记录,代码难免不尽人意。 The left-view of a binary tree is a list of nodes obtained by looking at the tree from left hand side and from top down. For example, given a tree shown by the figure, its left-view is { 1, 2, 3, 4, 5 } Given the inorder and preorder traversal sequences of a binary tree, you are supposed to output its left-vie

    2024年02月09日
    浏览(24)
  • LeetCode //C - 199. Binary Tree Right Side View

    Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.   Example 1: Input: root = [1,2,3,null,5,null,4] Output: [1,3,4] Example 2: Input: root = [1,null,3] Output: [1,3] Example 3: Input root = [] Output [] Constraints: The number of nodes in the tree is in t

    2024年01月20日
    浏览(35)
  • Leetcode 1367. Linked List in Binary Tree (二叉树好题)

    Linked List in Binary Tree Medium Given a binary tree root and a linked list with head as the first node. Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False. In this context downward path means a path that starts at some node and goes downwards. Exampl

    2024年01月25日
    浏览(47)
  • LeetCode //C - 114. Flatten Binary Tree to Linked List

    Given the root of a binary tree, flatten the tree into a “linked list”: The “linked list” should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. The “linked list” should be in the same order as a pre-order traversal of the binary tree.   Example 1: Input: ro

    2024年02月09日
    浏览(36)
  • LeetCode //C - 106. Construct Binary Tree from Inorder and Postorder Traversal

    Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.   Example 1: Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] Output: [3,9,20,null,null,15,7] Example 2: Input: inorder = [-1], postorder = [-1] Outpu

    2024年02月09日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包