[LeetCode] Find the Level of Tree with Minimum Sum

3157. Find the Level of Tree with Minimum Sum

Given the root of a binary tree root where each node has a value, return the level of the tree that has the minimum sum of values among all the levels (in case of a tie, return the lowest level).

Note that the root of the tree is at level 1 and the level of any other node is its distance from the root + 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* 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 minimumLevel(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
long long res = 0, sum = LLONG_MAX, lvl = 1;
while(q.size()) {
int qsz = q.size();
long long now = 0;
while(qsz--) {
auto n = q.front(); q.pop();
now += n->val;
if(n->left) q.push(n->left);
if(n->right) q.push(n->right);
}
if(now < sum) {
res = lvl;
sum = now;
}
lvl++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/06/26/PS/LeetCode/find-the-level-of-tree-with-minimum-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.