501.二叉搜索树中的众数

题目描述

假定 BST 有如下定义:

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

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

1

2
/
2

返回[2].

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-mode-in-binary-search-tree

解法1:进阶,用递归函数,节省空间,但是思路稍复杂

首先,应采用中序遍历的方法,这样得到的序列是递增的。使用两个指针pre,root来计算哪些数字是重复出现的众数。

代码如下:

/**
 * 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* root, TreeNode*& pre, int& curTimes, int& maxTimes, vector<int>& res)
    {
    if (!root) 
        return;
    inOrder(root->left, pre, curTimes, maxTimes, res);
    if (pre)
        curTimes = (root->val == pre->val) ? curTimes + 1 : 1;
    if (curTimes == maxTimes)
        res.push_back(root->val);
    else if (curTimes > maxTimes){
        res.clear();
        res.push_back(root->val);
        maxTimes = curTimes;
    }
    pre = root;
    inOrder(root->right, pre, curTimes, maxTimes, res);
}
vector<int> findMode(TreeNode* root) {
    vector<int> res;
    if (!root) return res;
    TreeNode* pre = NULL;
    int curTimes = 1, maxTimes = 0;
    inOrder(root, pre, curTimes, maxTimes, res);
    return res;
}
};

解法2:增加额外的空间,建立索引

同样使用中序遍历,将每个数字与它对应的次数建立索引,但是这道题目没有给定数字的范围,所以仅这种思路提供参考。最关键的问题,在最大次数的数字全部加入数组后,要删除数组中的重复元素。这里使用冒泡循环的方法。

/**
 * 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:
   vector<int> findMode(TreeNode* root) {
    vector<int> result;
	int i, max=0;
	recursive_postorder(root);
	int arr[10] = { 0 };
	for (i = 0; i < v.size(); i++)
	{
		arr[v[i]]++;
        if (arr[i] > max)
			max = arr[i];
	}
	for (i = 0; i < v.size(); i++)
	{
		if (max == v[i])
			result.push_back(v[i]);
	}
	for (int i = 0; i < result.size(); i++)    //冒泡循环
	{
		for (int j = result.size() - 1; j > i; j--)
		{
			if (result[j] == result[i])    //如果发现重复
			{
				if (j == result.size() - 1)    //如果是最后一个位置,直接len-1,继续循环
				{
					result.pop_back();
					continue;
				}
				for (int k = j + 1; k < result.size(); k++)
				{
					result[k - 1] = result[k];    //将后面的数依次赋值给前一个位置
				}
				result.pop_back();
			}
		}
	}
	return result;
}
    void recursive_postorder(TreeNode*& sub_root)
{
	if (sub_root != NULL)
	{
		recursive_postorder(sub_root->left);
		recursive_postorder(sub_root->right);
		v.push_back(sub_root->val);
	}
}
    private:
    vector<int> v;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值