2021.2.19 刷题(二叉树的众数)

题目链接:https://leetcode-cn.com/problems/find-mode-in-binary-search-tree
题目描述:
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树
方法一:树为普通二叉树
1.定义一个map记录节点值和节点出现的频率
2.对map中的节点按频率排序(不能直接对map的value排序,需要把map转化为vector再进行排序,vector里面放的是pair<int, int>类型的数据,第一个int为元素,第二个int为出现频率)
3.取高频元素,记录到结果数组

/**
 * 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:
  
    void travle(TreeNode* root, unordered_map<int, int>& map)
    {
        if(root == NULL) return;
        travle(root->left, map);
        map[root->val]++; //记录该节点频率
        travle(root->right, map);
    }
    bool static cmp(const pair<int, int>&a, const pair<int, int>&b)
    {
        return a.second > b.second;
    }
    
    vector<int> findMode(TreeNode* root) {
        unordered_map<int, int> map;  //key为节点,value为节点的频率
        vector<int> result;
        if(root == NULL)
            return result;
        travle(root, map);
        vector<pair<int, int>> vec(map.begin(), map.end()); //将map转为vector,按value排序
        sort(vec.begin(), vec.end(), cmp); //排序
        result.push_back(vec[0].first);
        for(int i = 1; i < vec.size(); i++)
        {
            if(vec[i].second == vec[0].second)
                result.push_back(vec[i].first);
            else
                break;
        }
        return result;
    }
};

方法二:树为搜索二叉树
1.使用了pre指针和cur指针。
每次cur(当前节点)和pre(前一个节点)作比较。初始化pre = NULL,这样当pre为NULL时候,我们就知道这是比较的第一个元素。
2.找最大频率的节点集合
由于搜索二叉树的中序遍历是一个有序数组,在遍历的过程中定义maxCount,如果count== maxCount,将该节点放入结果中,如果count> maxCount,更新maxCount且把之前的结果数组清空,重新更新结果数组。

/**
 * 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:
   int count;      //记录节点频率
   int maxCount;   //记录节点最大频率
   TreeNode* pre;  //前驱节点
   vector<int> result;   //结果数组
   void travle(TreeNode* cur)
   {
       if(cur == NULL) return;
       travle(cur->left);
       if(pre == NULL) //第一个节点
            count = 1;
        else if(pre->val == cur->val)
            count ++;
        else{
            count = 1;
        }
        pre = cur;  //更新节点
        if(count == maxCount)
            result.push_back(cur->val);
        if(count > maxCount)   //如果节点频率大于当前记录的最大频率,更新结果数组
        {
            maxCount = count;
            result.clear();
            result.push_back(cur->val);
        }
        travle(cur->right);
    }
    
    vector<int> findMode(TreeNode* root) {
       if(root == NULL) return result;
       travle(root);
       return result;
    }
};
posted @ 2021-02-19 20:48  张宵  阅读(43)  评论(0编辑  收藏  举报