DMSXL刷题(7)前k个高频元素|中序遍历二叉树|迭代法前序遍历二叉树|二叉树中序遍历迭代

347. 前 K 个高频元素 

给定一个非空的整数数组,返回其中出现频率前 k 高的元素。

示例 1:

  • 输入: nums = [1,1,1,2,2,3], k = 2
  • 输出: [1,2]

 

class Solution {
public:
     class mycomparison{
    public:
         bool operator()(const pair<int,int>&lhs,const pair<int,int>&rhs)
        {
            return lhs.second>rhs.second;
        }         
     };

    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int>map;
        for(int i=0;i<nums.size();i++)
        {
            map[nums[i]]++;
        }

        priority_queue<pair<int,int>,vector<pair<int,int>>,mycomparison> pri_que;

        for(unordered_map<int,int>::iterator it=map.begin();it!=map.end();it++)
        {
            pri_que.push(*it);
            if(pri_que.size()>k)
            {// 如果堆的大小大于了K,则队列弹出,保证堆的大小一直为k    
                pri_que.pop();
            }
        }
        // 找出前K个高频元素,因为小顶堆先弹出的是最小的
        vector<int>result;
        while(!pri_que.empty())
        {
            result.push_back(pri_que.top().first);
            pri_que.pop();
        }
        return result;
    }
};

94. 二叉树的中序遍历 

class Solution {
public:
    void Traversal(TreeNode*cur,vector<int>&vec)
    {
        if(cur==nullptr)
        return ;
        Traversal(cur->left,vec);
        vec.push_back(cur->val);
        Traversal(cur->right,vec);
    }
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int>result;
        Traversal(root,result);
        return result;
    }
};

144. 二叉树的前序遍历

class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
    stack<TreeNode*>st;
    vector<int>vec;
    if(root==nullptr)return vec;
    st.push(root);
    while(!st.empty())
    {
        TreeNode*node=st.top();
        st.pop();
        vec.push_back(node->val);
        if(node->right)st.push(node->right);
        if(node->left)st.push(node->left);
    }
    return vec;
    
    }
};

94. 二叉树的中序遍历

class Solution {
public:
    vector<int>inorderTraversal(TreeNode*root)
    {
        stack<TreeNode*>st;
        vector<int>result;
        TreeNode* cur=root;
        while(cur!=nullptr||!st.empty())
        {
            if(cur!=nullptr)
            {
                st.push(cur);
                cur=cur->left;
            }
            else
            {  
               cur=st.top();
               st.pop(); 
                result.push_back(cur->val);
                cur=cur->right;
            }
        }
        return result;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值