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]
题目大意:输出树的每一层的最大值
解题思路:广度优先遍历图,输出每一层的最大值
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
queue<TreeNode *> que;
vector<int> vec;
if (!root) return vec;
que.push(root);
while(!que.empty()) {
int size = que.size();
int max = INT_MIN;
while (size--) {
TreeNode *node = que.front();
que.pop();
if(node->val > max) max = node->val;
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
vec.push_back(max);
}
return vec;
}
};