0
点赞
收藏
分享

微信扫一扫

剑指offer专项突击--第十五天

汤姆torn 2022-04-05 阅读 70
c++leetcode

剑指 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;
    }
};
举报

相关推荐

HCIP 第十五天

HCIP第十五天

第十五天6号

学习javaweb第十五天

打卡学习第十五天

Java web第十五天

0 条评论