题目:给定一颗二叉树,求每一层节点中的最大值。例子如下:
Input: 1 / \ 3 2 / \ \ 5 3 9 Output: [1, 3, 9]
其实,解决这道题目的思路很简单,跟之前写过的一两道二叉树的题目差不多。问题是,我们怎么知道每一层的开始跟结束呢?这里还是要用到我经常用的vector,利用它来实现每一层的遍历。道理很简单,我们先把根节点放进vecotr中,然后我们根据vector.size就可以知道每一层的节点数,利用size去遍历每一层的节点,同时把节点的子节点放进vector中,并找出最大值。而遍历后的节点就弹出vector,这样一个循环下来,vector中存放的都是下一层未遍历的节点。代码如下:
/**
* 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:
vector<int> largestValues(TreeNode* root) {
queue<TreeNode*> nodes;
vector<int> result;
if (!root) return result;
nodes.push(root);
while (!nodes.empty()) {
int size = nodes.size();
int max = nodes.front()->val;
TreeNode* temp;
for (int i = 0; i < size; i++) {
temp = nodes.front();
if (temp->val > max) max = temp->val;
if (temp->left) nodes.push(temp->left);
if (temp->right) nodes.push(temp->right);
nodes.pop();
}
result.push_back(max);
}
return result;
}
};
本文介绍了一种使用队列实现的二叉树层序遍历算法,通过该算法可以找到每层节点的最大值。具体实现利用了vector容器来辅助遍历过程,详细解释了如何确定每层节点的数量并更新最大值。
425

被折叠的 条评论
为什么被折叠?



