酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

C 语言用二叉搜索树(模拟 set )实现查找数组第三大数字

以下是一个使用 C 语言的`set`(通过二叉搜索树实现)来解决此问题的示例代码: ```c #include <stdio.h> #include <stdlib.h> // 二叉搜索树的节点结构 typedef struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; } TreeNode; // 创建新节点 TreeNode* createNode(int val) { TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode)); newNode->val = val; newNode->left = NULL; newNode->right = NULL; return newNode; } // 插入节点到二叉搜索树 TreeNode* insert(TreeNode* root, int val) { if (root == NULL) { return createNode(val); } if (val < root->val) { root->left = insert(root->left, val); } else if (val > root->val) { root->right = insert(root->right, val); } return root; } // 中序遍历二叉搜索树 void inorderTraversal(TreeNode* root) { if (root!= NULL) { inorderTraversal(root->left); printf("%d ", root->val); inorderTraversal(root->right); } } // 查找第三大的数 int findThirdLargest(int arr[], int size) { TreeNode* root = NULL; for (int i = 0; i < size; i++) { root = insert(root, arr[i]); } int count = 0; int result = -1; inorderTraversal(root); printf("\n"); TreeNode* curr = root; while (curr!= NULL) { if (curr->right == NULL) { if (++count == 3) { result = curr->val; break; } curr = curr->left; } else { TreeNode* successor = curr->right; while (successor->left!= NULL && successor->left!= curr) { successor = successor->left; } if (successor->left == NULL) { successor->left = curr; curr = curr->right; } else { successor->left = NULL; if (++count == 3) { result = curr->val; break; } curr = curr->left; } } } if (result == -1) { result = root->val; } return result; } int main() { int arr[] = {2, 2, 3, 1}; int size = sizeof(arr) / sizeof(arr[0]); int thirdLargest = findThirdLargest(arr, size); printf("第三大的数是: %d\n", thirdLargest); return 0; } ``` 这段代码首先创建了一个二叉搜索树来存储数组中的元素,然后通过遍历树来找到第三大的数。如果不存在第三大的数,则返回最大的数。 ######[AI写代码神器 | 737点数解答 | 2024-09-12 23:09:16]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]