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较为简单。 C++代码:
/**
* 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> vec;
if(!root){
return vec;
}
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int res = -; //int类型的最小数。
for(int i = q.size(); i > ; i--){
auto t = q.front();
q.pop();
if(t->val > res){
res = t->val;
}
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
vec.push_back(res);
}
return vec;
}
};