Problem
You need to find the largest value in each row of a binary tree.
Example:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
Solution
题意
输入一个二叉树,要求求出每层的最大值。
分析
这道题和刚刚那道#513非常相似,解决思路也差不多,通过层序遍历找出每层的最大值。
在#513的代码基础上做一些细微的改动即可。
Code
/**
* 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) {
/* 在#513的基础上做少许改动,即在每层取得最大值,即可解决这个问题 */
vector<int> result;
queue<TreeNode *> q;
if (root != NULL)
q.push(root);
else
return result;
while(!q.empty()){
int size = q.size();
int max = q.front()->val;
/* 逐层遍历 */
for (int i = 0; i < size; i++){
TreeNode * now = q.front();
q.pop();
if (now->val >= max)
max = now->val;
if (now->left != NULL)
q.push(now->left);
if (now->right != NULL)
q.push(now->right);
}
result.push_back(max);
}
return result;
}
};
//Runtime:15ms