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]思路:广度优先遍历
代码1:
/**
* 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> result,nums;
if (root == NULL) {
return result;
}
queue<TreeNode*> s;
int maxno,len=0;
s.push(root);
while(!s.empty()){
len=s.size();
for(int i=0;i<len;i++){
TreeNode* node=s.front();
s.pop();
nums.push_back(node->val);
if(node->left != NULL) {s.push(node->left);}
if(node->right != NULL) {s.push(node->right);}
}
maxno=*max_element(nums.begin(),nums.end());
result.push_back(maxno);
nums.clear();
}
return result;
}
};
代码2:
/**
* 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> res;
if(root==NULL){return res;}
queue<TreeNode*> sp;
sp.push(root);
int maxval;
while(!sp.empty()){
auto temp=sp.front();
maxval=temp->val;
int len=sp.size();
for(int i=0;i<len;i++){
auto temp=sp.front();
sp.pop();
if(maxval<(temp->val)){maxval=temp->val;}
if(temp->left!=NULL){sp.push(temp->left);}
if(temp->right!=NULL){sp.push(temp->right);}
}
res.push_back(maxval);
}
return res;
}
};