【LeetCode】1161.Maximum Level Sum of a Binary Tree解題報告(C++)
6784 ワード
目次
タイトルの説明
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:
Input: [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.
Note:
-10^5 <= node.val <= 10^5
テーマの大意
ツリーの1階のノードと、最大のときの最小層番号.
解題方法
BFS
この問題は階層遍歴であり、BFSとDFSの2つの方法があり、類似の問題は102である.Binary Tree Level Order Traversal.ここではBFSを使用しています.
BFSは、現在のレイヤのすべてのリーフノードをキューに格納し、キューを出て、そのレイヤのすべてのリーフノードを合計する必要がある.
タイトルは最大と出現の最小レイヤ番号を要求するので,現在のレイヤの和が以前のレイヤより大きい場合,結果のレイヤ番号を修正すると判断する.
C++コードは以下の通りです.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxLevelSum(TreeNode* root) {
int res_sum = INT_MIN;
int res_level = 1;
queue<TreeNode*> que;
que.push(root);
int level = 1;
while (!que.empty()) {
int size = que.size();
int level_sum = 0;
while (size --) {
TreeNode* cur = que.front(); que.pop();
if (!cur) continue;
level_sum += cur->val;
que.push(cur->left);
que.push(cur->right);
}
if (level_sum > res_sum) {
res_sum = level_sum;
res_level = level;
}
level ++;
}
return res_level;
}
};
日付
2019年9月27日——昨日は速手で、意外にも純粋なブラシの問題です