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