C语言找出二叉查找树中出现频率最高的元素
时间: 2024-03-10 12:49:16 浏览: 12
要找出二叉查找树中出现频率最高的元素,可以按照以下步骤进行:
1. 对二叉查找树进行中序遍历,得到有序的元素序列。
2. 遍历该序列,使用哈希表记录每个元素出现的次数。
3. 遍历哈希表,找到出现次数最多的元素,即为所求。
以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct TreeNode {
int val;
int freq;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct HashTable {
int key[MAX_SIZE];
int value[MAX_SIZE];
int size;
} HashTable;
// 创建哈希表
HashTable *createHashTable() {
HashTable *hashTable = (HashTable *) malloc(sizeof(HashTable));
hashTable->size = 0;
for (int i = 0; i < MAX_SIZE; i++) {
hashTable->key[i] = 0;
hashTable->value[i] = 0;
}
return hashTable;
}
// 向哈希表中插入元素
void insert(HashTable *hashTable, int key, int value) {
int i;
for (i = 0; i < hashTable->size; i++) {
if (hashTable->key[i] == key) {
hashTable->value[i] += value;
return;
}
}
hashTable->key[i] = key;
hashTable->value[i] = value;
hashTable->size++;
}
// 中序遍历二叉查找树
void inorder(TreeNode *root, HashTable *hashTable) {
if (root == NULL) {
return;
}
inorder(root->left, hashTable);
insert(hashTable, root->val, 1);
inorder(root->right, hashTable);
}
// 创建二叉查找树
TreeNode *createBST(int arr[], int n) {
if (n <= 0) {
return NULL;
}
TreeNode *root = (TreeNode *) malloc(sizeof(TreeNode));
root->val = arr[n / 2];
root->freq = 1;
root->left = createBST(arr, n / 2);
root->right = createBST(arr + n / 2 + 1, n - n / 2 - 1);
return root;
}
// 找出出现频率最高的元素
int findMostFrequentElement(HashTable *hashTable) {
int maxFreq = 0;
int mostFrequent = 0;
for (int i = 0; i < hashTable->size; i++) {
if (hashTable->value[i] > maxFreq) {
maxFreq = hashTable->value[i];
mostFrequent = hashTable->key[i];
}
}
return mostFrequent;
}
int main() {
int arr[] = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5};
int n = sizeof(arr) / sizeof(arr[0]);
TreeNode *root = createBST(arr, n);
HashTable *hashTable = createHashTable();
inorder(root, hashTable);
int mostFrequent = findMostFrequentElement(hashTable);
printf("The most frequent element is: %d\n", mostFrequent);
return 0;
}
```
该程序首先创建了一个有序的序列,然后按照上述步骤依次进行中序遍历、哈希表记录和查找出现频率最高的元素。在此示例中,结果为 5。