您需要在二叉树的每一行中找到最大的值。
示例:
输入: 1 / \ 3 2 / \ \ 5 3 9 输出: [1, 3, 9]
思路:
采用层序遍历,每层通过变量max_保存这一层的最大值,然后加到res中即可。
vector<int> largestValues(TreeNode* root) {
vector<int> res;
if (!root) {
return res;
}
queue<TreeNode*> queue;
queue.push(root);
while (!queue.empty()) {
int length = queue.size();
int max_ = INT_MIN;
for (int i = 0; i < length; i++) {
TreeNode* tmp = queue.front();
max_ = max(max_, tmp->val);
if (tmp->left) {
queue.push(tmp->left);
}
if (tmp->right) {
queue.push(tmp->right);
}
queue.pop();
}
res.push_back(max_);
}
return res;
}