- 二叉搜索树中的众数
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树
例如:
给定 BST [1,null,2,2],
借鉴一位大佬代码:
C语言解决代码:
void find(struct TreeNode* root, int *array, int *max, int *count, int *data, int *i){
if (!root)
return ;
else
{
find(root->left, array, max, count, data, i);
if (root->val == *data)//前一个节点与当前节点数值相同 采用二叉搜索树的中序遍历
{
*count = *count + 1;
}
else if (root->val != *data && *data != -99999)
{
if (*count > *max)
{
*max = *count;
*i = 0;//重置
array[*i] = *data;
*i = *i + 1;//所以i一般停留在1这个位置上
}
else if (*count == *max)
{
array[*i] = *data;
*i = *i + 1;
}
*count = 1;//次数重新置为1
}
*data = root->val;//取得当前的数值
find(root->right, array, max, count, data, i);
}
}
int* findMode(struct TreeNode* root, int* returnSize){
if (root == NULL)
{
*returnSize = 0;
return NULL;
}
int *array = malloc(sizeof(int) * 10000);
int i, max = 0, count = 1, data = -99999;
//i=0;
find(root, array, &max, &count, &data, &i);//array地址空间已经开辟 所以传递地址过去 对方用指针接受就可操纵空间
if (count == max)//最后一个节点 count没有来得及与max比较
{
array[i] = data;
i++;
}
else if (count > max)
{
i = 0;
array[i++] = data;
}
*returnSize = i;//返回的个数
return array;
}