剑指 Offer II 044. 二叉树每层的最大值
广搜取每一层最大值
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
queue<TreeNode*>q;
q.push(root);
vector<int>ans;
if(!root) return ans;
int mmax = INT_MIN;
while(!q.empty()){
int len = q.size();
mmax = INT_MIN;
for(int i = 0; i < len; i++){
auto r = q.front();
mmax = max(mmax,r->val);
if(r->left) q.push(r->left);
if(r->right) q.push(r->right);
q.pop();
}
ans.push_back(mmax);
}
return ans;
}
};
剑指 Offer II 045. 二叉树最底层最左边的值
广搜取第一个值
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*>q;
q.push(root);
int ans;
while(!q.empty()){
int len = q.size();
for(int i = 0; i < len; i++){
auto r = q.front();
if(i == 0) ans = r->val;
if(r->left) q.push(r->left);
if(r->right) q.push(r->right);
q.pop();
}
}
return ans;
}
};
剑指 Offer II 046. 二叉树的右侧视图
广搜取最后一个值
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int>ans;
queue<TreeNode*>q;
q.push(root);
if(!root) return ans;
while(!q.empty()){
int len = q.size();
for(int i = 0; i < len; i++){
auto r = q.front();
if(i == len - 1) ans.push_back(r->val);
if(r->left) q.push(r->left);
if(r->right) q.push(r->right);
q.pop();
}
}
return ans;
}
};