c语言二叉链表创建二叉树实现二叉树的基本功能
时间: 2024-12-12 12:14:09 浏览: 10
在C语言中,我们可以使用结构体表示二叉树节点,并通过链表的方式来构建二叉树。首先,定义一个二叉树节点的结构:
```c
typedef struct TreeNode {
int val; // 节点值
struct TreeNode* left; // 左子节点指针
struct TreeNode* right; // 右子节点指针
} TreeNode;
```
接下来,我们可以通过递归的方式实现基本的二叉树操作:
1. **创建空树**:
```c
TreeNode* createEmptyTree() {
return NULL;
}
```
2. **插入节点**:
```c
TreeNode* insertNode(TreeNode* root, int val) {
if (root == NULL) {
root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = val;
root->left = root->right = NULL;
} else if (val < root->val) {
root->left = insertNode(root->left, val);
} else {
root->right = insertNode(root->right, val);
}
return root;
}
```
3. **查找节点**:
```c
TreeNode* searchNode(TreeNode* root, int val) {
if (root == NULL || root->val == val)
return root;
if (val < root->val)
return searchNode(root->left, val);
return searchNode(root->right, val);
}
```
4. **遍历**(如前序、中序、后序等):
- 前序遍历:`void preOrderTraversal(TreeNode* root, void (*visit)(int))`
- 中序遍历:`void inOrderTraversal(TreeNode* root, void (*visit)(int))`
- 后序遍历:`void postOrderTraversal(TreeNode* root, void (*visit)(int))`
5. **删除节点**(涉及更复杂的逻辑,包括找子节点替换、更新链接等):
```c
TreeNode* deleteNode(TreeNode* root, int val) {
if (root == NULL)
return root;
if (val < root->val)
root->left = deleteNode(root->left, val);
else if (val > root->val)
root->right = deleteNode(root->right, val);
else { // 找到要删除的节点
if (root->left == NULL && root->right == NULL) {
free(root); // 如果无子节点,直接释放内存
} else if (root->left == NULL) {
TreeNode* temp = root;
root = root->right;
free(temp);
} else if (root->right == NULL) {
TreeNode* temp = root;
root = root->left;
free(temp);
} else { // 有左右两个子节点,找到右子树最小节点替换
TreeNode* minNode = findMin(root->right);
root->val = minNode->val;
root->right = deleteNode(root->right, minNode->val);
}
}
return root;
}
TreeNode* findMin(TreeNode* node) {
while (node->left != NULL)
node = node->left;
return node;
}
```
阅读全文