#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value, height;
struct Node* left;
struct Node* right;
} Node;
int height(const Node* n) { return n ? n->height : 0; }
int balanceFactor(const Node* n) { return height(n->left) - height(n->right); }
int maxInt(int a, int b) { return a > b ? a : b; }
Node* newNode(int value) {
Node* n = calloc(1, sizeof(Node));
n->value = value;
n->height = 1;
return n;
}
void updateHeight(Node* n) {
n->height = 1 + maxInt(height(n->left), height(n->right));
}
Node* rotateRight(Node* y) {
Node* x = y->left;
y->left = x->right;
x->right = y;
updateHeight(y);
updateHeight(x);
return x;
}
Node* rotateLeft(Node* x) {
Node* y = x->right;
x->right = y->left;
y->left = x;
updateHeight(x);
updateHeight(y);
return y;
}
Node* insert(Node* node, int value) {
if (node == NULL) return newNode(value);
if (value < node->value) node->left = insert(node->left, value);
else node->right = insert(node->right, value);
updateHeight(node);
int balance = balanceFactor(node);
// Four rebalancing cases: LL, RR, LR, RL
if (balance > 1 && value < node->left->value) return rotateRight(node);
if (balance < -1 && value > node->right->value) return rotateLeft(node);
if (balance > 1) {
node->left = rotateLeft(node->left);
return rotateRight(node);
}
if (balance < -1) {
node->right = rotateRight(node->right);
return rotateLeft(node);
}
return node;
}
void inorder(const Node* n) {
if (n == NULL) return;
inorder(n->left);
printf("%d(h%d) ", n->value, n->height);
inorder(n->right);
}
int main(void) {
int values[] = {10, 20, 30, 40, 50, 25};
Node* root = NULL;
for (int i = 0; i < 6; i++) root = insert(root, values[i]);
printf("Root after rebalancing: %d\n", root->value);
printf("In-order: ");
inorder(root);
printf("\n");
return 0;
}
在浏览器中在线编译和运行 C 代码
这是一个免费的 C 语言在线编辑器和编译器。在浏览器里写 C 代码,点击运行,gcc 会在几秒内编译并执行你的程序。不用先在本地装 gcc 或 clang,也不用配置 make 或 CMake。
编辑器基于与 VS Code 相同的引擎,C 语法高亮、自动补全和错误波浪线提示一应俱全。代码在 Alpine Linux 上用 gcc 编译,链接 musl libc,可以使用完整的 C99/C11 标准库:<stdio.h>、<stdlib.h>、<string.h>、<math.h>、<time.h>、<stdint.h>。无论是排查段错误、验证位运算技巧,还是准备 C 语言面试,都很合适。要写 C++?请使用 C++ 在线编译器。
这个 C 语言在线编辑器好用在哪里
即时编译 C 代码:写好代码,点击运行,几秒内就能看到在线 gcc 编译器的输出,不需要 Makefile 或 CMake。
完整的 C 语法高亮、头文件自动补全和清晰的 gcc 诊断信息,由 VS Code 同款编辑器引擎提供支持。
支持标准输入。scanf、getchar、fgets(buf, n, stdin) 都会从编辑器的输入框读取数据,交互式程序和面试题不用搭建项目就能直接运行。你的电脑上无需安装 gcc、clang、MinGW 或 WSL。
基于 Alpine Linux 的 gcc 编译器:用指针、结构体和完整的 C99/C11 标准库写 C 代码,一键编译并运行。
在 C 语言在线编辑器里可以做什么
指针运算、数组和字符串处理:这些 C 语言核心写法都可以用 printf 调试一步步看清楚。
手写数据结构(链表、二叉树、哈希表),再配合经典算法(排序、BFS、DFS、递归),直观理解 C 语言如何暴露内存布局。
快速做 C 语言小实验:测试一个格式说明符,查看结构体的 sizeof,验证位掩码,或者确认运算符的结合方向,都不用先写 Makefile。