思路:BFS广度优先搜索,用for循环依次搜索树的每一层。
这道题目很经典
/**
* 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) {
queue<TreeNode*> q;
vector<int> v;
if (!root) return v;
TreeNode* p = root;
q.push(p);
while (!q.empty())
{
int size = q.size(), max = INT_MIN;
for (int i = 0; i < size; ++i)
{
p = q.front();
q.pop();
if (p->val > max) max = p->val;
if (p->left) q.push(p->left);
if (p->right) q.push(p->right);
}
v.push_back(max);
}
return v;
}
};