501. 二叉搜索树中的众数(C++)

题目详情

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

假定 BST 有如下定义:

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

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

   1
    \
     2
    /
   2
返回[2].

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

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

 

——题目难度:简单


 





-下面代码(带注释)

/**
 * 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 {
private:
	vector<int> ans; //最后的结果数组 
	
	/*中序遍历*/ 
	void inOrder(TreeNode *root, TreeNode *&pre, int &cur_count, int &max_count, int &ans_size) {
		if (root == NULL) return ;
		
		inOrder(root->left, pre, cur_count, max_count, ans_size); //先左 
		
		if (pre && root->val == pre->val) {
			cur_count++;
		} else {
			cur_count = 1;
		}
		
		if (cur_count > max_count) {
			max_count = cur_count;
			ans_size = 1;
		} 
		else if (cur_count == max_count) {
			if (!ans.empty()) { //第一次中序遍历不会进入这里面 
				ans[ans_size] = root->val;
			}
			ans_size++;
		}
		
		pre = root;
		
		inOrder(root->right, pre, cur_count, max_count, ans_size); //后右 
	}
	
public:
    vector<int> findMode(TreeNode* root) {
		int max_count = 0; //众数的出现次数
		int cur_count = 0; //当前元素的出现次数
		int ans_size = 0; //结果数组的长度
		
		TreeNode *pre = NULL; //pre指向上一次的元素 
		inOrder(root, pre, cur_count, max_count, ans_size); //第一次中序遍历
		
		ans.resize(ans_size);
		ans_size = 0;
		pre = NULL;
		cur_count = 0;
		inOrder(root, pre, cur_count, max_count, ans_size); //第二次中序遍历
		
		return ans; 
    }
};

结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

重剑DS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值