抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。


思路

  • 层序遍历,记录每层的最大值。

学习点

代码

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
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> res;
if (!root)
return res;
queue<TreeNode*> qe;
qe.push(root);
while (!qe.empty())
{
int node_num = qe.size();
int max_of_level = qe.front()->val;

for (int i = 0; i < node_num; i++)
{
auto tmp = qe.front();
qe.pop();

if (max_of_level < tmp->val)
max_of_level = tmp->val;

if (tmp->left)
qe.push(tmp->left);
if (tmp->right)
qe.push(tmp->right);
}

res.push_back(max_of_level);
}

return res;
}
};