Skip to content

Commit e2c0d05

Browse files
committed
chore: sync automated leetcode submissions with Runtime - 0 ms (100.00%), Memory - 3 MB (100.00%)
1 parent 11a4368 commit e2c0d05

2 files changed

Lines changed: 78 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<p>Given the <code>root</code> of a binary tree, the level of its root is <code>1</code>, the level of its children is <code>2</code>, and so on.</p>
2+
3+
<p>Return the <strong>smallest</strong> level <code>x</code> such that the sum of all the values of nodes at level <code>x</code> is <strong>maximal</strong>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
<img alt="" src="https://assets.leetcode.com/uploads/2019/05/03/capture.JPG" style="width: 200px; height: 175px;" />
8+
<pre>
9+
<strong>Input:</strong> root = [1,7,0,7,-8,null,null]
10+
<strong>Output:</strong> 2
11+
<strong>Explanation: </strong>
12+
Level 1 sum = 1.
13+
Level 2 sum = 7 + 0 = 7.
14+
Level 3 sum = 7 + -8 = -1.
15+
So we return the level with the maximum sum which is level 2.
16+
</pre>
17+
18+
<p><strong class="example">Example 2:</strong></p>
19+
20+
<pre>
21+
<strong>Input:</strong> root = [989,null,10250,98693,-89388,null,null,null,-32127]
22+
<strong>Output:</strong> 2
23+
</pre>
24+
25+
<p>&nbsp;</p>
26+
<p><strong>Constraints:</strong></p>
27+
28+
<ul>
29+
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
30+
<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
31+
</ul>
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
use std::rc::Rc;
2+
use std::cell::RefCell;
3+
use std::collections::VecDeque;
4+
5+
impl Solution {
6+
pub fn max_level_sum(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
7+
let root = match root {
8+
Some(node) => node,
9+
None => return 0,
10+
};
11+
12+
let mut max_sum = i32::MIN;
13+
let mut max_level = 1;
14+
let mut current_level = 1;
15+
16+
let mut queue = VecDeque::new();
17+
queue.push_back(root);
18+
19+
while !queue.is_empty() {
20+
let level_size = queue.len();
21+
let mut level_sum = 0;
22+
23+
for _ in 0..level_size {
24+
if let Some(node) = queue.pop_front() {
25+
let node_borrow = node.borrow();
26+
level_sum += node_borrow.val;
27+
28+
if let Some(left) = node_borrow.left.clone() {
29+
queue.push_back(left);
30+
}
31+
if let Some(right) = node_borrow.right.clone() {
32+
queue.push_back(right);
33+
}
34+
}
35+
}
36+
37+
if level_sum > max_sum {
38+
max_sum = level_sum;
39+
max_level = current_level;
40+
}
41+
42+
current_level += 1;
43+
}
44+
45+
max_level
46+
}
47+
}

0 commit comments

Comments
 (0)