LeetCode501. 二叉搜索树中的众数(C++实现)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28584889/article/details/85111746

题目描述

给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。

假定 BST 有如下定义:

  • 结点左子树中所含结点的值小于等于当前结点的值
  • 结点右子树中所含结点的值大于等于当前结点的值
  • 左子树和右子树都是二叉搜索树

例如:
给定 BST [1,null,2,2],

   1
    \
     2
    /
   2

返回[2].

提示:如果众数超过1个,不需考虑输出顺序

进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)

解题思路

利用二叉搜索树(即二叉排序树)的性质:中序遍历是一个升序序列,定义一个全局的preNum变量用于存储上一次遍历的节点值,中序遍历时用当前节点的值跟preNum比较,比较完要及时更新记录当前元素出现的次数的curTimes,以及元素出现的最大次数maxTimes;遍历右子树前还要更新preNum的值。

代码详解

/**
 * 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 inorder(TreeNode* T, vector<int>& multiNums, int& curTimes, int& maxTimes, int& preNum) //中序遍历的递归调用函数
    {
        if(T->left) //如果左子树不为空,遍历左子树
            inorder(T->left, multiNums, curTimes, maxTimes, preNum);
        curTimes = preNum == T->val ? curTimes + 1 : 1; //更新当前元素出现的次数
        if(curTimes > maxTimes) //更新maxTimes,当出现更大的maxTimes时,数组清空之后再存如当前元素
        {
            maxTimes = curTimes;
            multiNums.clear(); 
            multiNums.push_back(T->val);
        }else if(curTimes == maxTimes){ //相等时就将当前元素也存入数组
            multiNums.push_back(T->val);
        }
        preNum = T->val; //更新preNum
        if(T->right)//遍历右子树
            inorder(T->right, multiNums, curTimes, maxTimes, preNum);
    }

    vector<int> findMode(TreeNode* root) {
        vector<int> res;
        if(root == NULL)
            return res;
        int curTimes = 1, maxTimes = 0, preNum = INT_MIN;
        inorder(root, res, curTimes, maxTimes, preNum);
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_28584889/article/details/85111746
今日推荐