501.二叉搜索树中的众数
题目描述
解题方法
先中序遍历存放在一个数组中,再求数组众数,代码如下,未通过。思路没问题,但是执行的时候没问题,提交就WA了。
int arr[1024];
int res[100];
int resSub = 0;
int num = 0;
int arrLen = 0;
void arrInit()
{
memset(arr, 0xfffffffe, sizeof(int) * 1024);
memset(res, 0xfffffffe, sizeof(int) * 100);
}
void Inorder(struct TreeNode* root) //中序遍历
{
if (root != NULL)
{
Inorder(root->left);
//printf("%c", T->data);
arr[num++] = root->val;
arrLen ++; // 数组长度
Inorder(root->right);
}
}
int nowNum,preNum = 0xfffffffe, preSize = 1, maxSize = 0;
int* findMode(struct TreeNode* root, int* returnSize)
{
arrInit();
Inorder(root); // 中序遍历得到递增数组
for (int i = 0; i < arrLen; i ++)
{
printf("%d\n", arr[i]);
}
printf("arrlen = %d\n", arrLen);
*returnSize = 1;
preNum = arr[0];
res[0] = arr[0]; // 避免单节点输入
for (int i = 1; i < arrLen; i ++)
{
nowNum = arr[i];
if (preNum == nowNum)
{
preSize ++; //这里两个数相同
}
else if (preNum != nowNum)
{
if (preSize > maxSize)
{
maxSize = preSize; // 更新值
*returnSize = 1;
resSub = 0;
res[resSub++] = preNum;
}
else if (preSize == maxSize)
{
res[resSub++] = preNum;
*returnSize ++;
}
preNum = nowNum; // 更新preNum
preSize = 1; // 重新设置为 1
}
}
if (preSize > maxSize) // 防止众数出现在最后一个数
{
maxSize = preSize; // 更新值
*returnSize = 1;
resSub = 0;
res[resSub++] = preNum;
}
else if (preSize == maxSize)
{
res[resSub++] = preNum;
*returnSize ++;
}
return res;
}