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]
考察: 树的层序遍历/BFS
/**
* 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> v;
deque<TreeNode*> dq;
if(root!=nullptr)
dq.push_back(root);
TreeNode* node = nullptr;
while(!dq.empty())
{
int sz = dq.size(); // 记录每行个数
int max = dq.front()->val;
for(int i=0;i<sz;++i)
{
node = dq.front();
max = max > node->val ? max :node->val;
dq.pop_front();
if(node->left)
dq.push_back(node->left);
if(node->right)
dq.push_back(node->right);
}
v.push_back(max);
}
return v;
}
};