Open songyy5517 opened 5 months ago
Approach: BFS
max_layer
: records the number of the layer with the maximum node sum;max_sum
: records the global maximum layer node sum;cur_layer
: the current layer that is travarsing;max_layer
;Complexity Analysis
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxLevelSum(TreeNode root) {
// Intuition: BFS, calculate the sum of each layer
// 1. Exception handling
if (root == null)
return 0;
// 2. Define variables
int cur_layer = 1, max_layer = 1, max_sum = root.val;
Queue<TreeNode> queue = new LinkedList();
queue.add(root);
// 3. BFS
while (!queue.isEmpty()){
int node_num = queue.size();
int sum = 0;
for (int i = 0; i < node_num; i++){
TreeNode cur = queue.remove();
sum += cur.val;
if (cur.left != null) queue.add(cur.left);
if (cur.right != null) queue.add(cur.right);
}
if (sum > max_sum){
max_sum = sum;
max_layer = cur_layer;
}
cur_layer ++;
}
return max_layer;
}
}
2024/6/7
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:
Example 2:
Intuition The problem is basicallly to find the layer with the maximum sum of its nodes. A straightforward idea is to travarse the whole tree using BFS. For each layer, we calculate the sum of all its nodes and compare with the global maximum sum.