您需要在二叉树的每一行中找到最大的值。
示例:
输入:
1
/ \
3 2
/ \ \
5 3 9
输出: [1, 3, 9]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* 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) {
vector<int> result;
if (root == NULL) {
return result;
}
queue<TreeNode *> Q;
Q.push(root);
while (!Q.empty()) {
int size = Q.size();
//vector<int> level;
int tmpmax = INT_MIN;
for (int i = 0; i < size; i++) {
TreeNode *head = Q.front(); Q.pop();
//level.push_back(head->val);
tmpmax = max(tmpmax, head->val);
if (head->left != NULL) {
Q.push(head->left);
}
if (head->right != NULL) {
Q.push(head->right);
}
}
result.push_back(tmpmax);
}
return result;
}
};