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]
- C++ 实现:精准统计给定范围 [L, R] 内数字 2 出现的次数及代码详解(字节豆包 | 401点数解答 | 2026-02-05 21:17:05)60
- C++实现:统计[L, R]范围内数字2出现的次数及代码详解(字节豆包 | 489点数解答 | 2026-02-07 17:12:26)75
- Python 实现球类:精准计算半径、表面积与体积,附输入验证与异常处理!(阿里通义 | 261点数解答 | 2024-11-28 21:19:39)371
- SQL:[pr_createdtables]存储过程代码解析及表创建准备 (字节豆包 | 33点数解答 | 2024-08-29 15:34:33)359
- SQL 修正:创建带唯一索引的 py_plan_opportunity_point 表(阿里通义 | 328点数解答 | 2024-09-04 16:07:48)325
- "MySQL: Creating the 'py_plan_opportunity_point' Table with Unique Location Codes"(阿里通义 | 188点数解答 | 2024-09-04 16:08:40)447
- MySQL:完整创建 py_plan_opportunity_point 表及字段详解(阿里通义 | 348点数解答 | 2024-09-04 16:09:36)293
- "SQL条件判断下的角色数据更新操作揭秘"(GPT | 51点数解答 | 2024-10-22 11:24:35)305
- "Enhanced SQL Script for SRO MMORPG Database: Conditional Updates, Transactions & Logging"(阿里通义 | 969点数解答 | 2024-10-22 11:26:02)383
- 巧用集合:计算输入正整数中等于两数之和的数量(字节豆包 | 558点数解答 | 2025-11-24 19:19:24)48
- Python:用正则表达式从含多种字符的字符串中提取英文、数字和中文单词(GPT | 522点数解答 | 2024-05-31 19:05:27)335
- Python:用正则表达式结合 split 思路提取一行字符串中的英文、数字和中文单词 (GPT | 399点数解答 | 2024-05-31 19:07:31)328