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]
/**
* 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) {
if(!root) return vector<int>();
queue<TreeNode *> q;
q.push(root);
int current = 1;
int next = 0;
vector<int> ret;
int max = INT_MIN;
while(!q.empty())
{
TreeNode * node = q.front();
q.pop();
if(node->val > max) max = node->val;
if(node->left)
{
next++;
q.push(node->left);
}
if(node->right)
{
next++;
q.push(node->right);
}
if(--current == 0)
{
current = next;
next = 0;
ret.push_back(max);
max = INT_MIN;
}
}
return ret;
}
};