用C语言编写链表式二叉树,其中包含二叉树的初始化,节点的插入,节点的删除
时间: 2023-05-29 13:01:14 浏览: 114
//定义二叉树节点
typedef struct TreeNode {
int value;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
//初始化二叉树
TreeNode *initBinaryTree() {
return NULL;
}
//插入节点
TreeNode *insertNode(TreeNode *root, int value) {
//如果当前节点为空,则代表到了应该插入的位置
if (root == NULL) {
TreeNode *newNode = (TreeNode *) malloc(sizeof(TreeNode));
newNode->value = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
//如果当前节点的值小于待插入的值,则往右子树插入
if (root->value < value) {
root->right = insertNode(root->right, value);
}
//如果当前节点的值大于待插入的值,则往左子树插入
else if (root->value > value) {
root->left = insertNode(root->left, value);
}
return root;
}
//删除节点
TreeNode *deleteNode(TreeNode *root, int value) {
//递归到要删除的节点,或者该节点不存在
if (root == NULL) {
return NULL;
} else if (root->value > value) {
root->left = deleteNode(root->left, value);
} else if (root->value < value) {
root->right = deleteNode(root->right, value);
} else { //找到了要删除的节点
//该节点没有子节点或只有一个子节点
if (root->left == NULL) {
TreeNode *temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
TreeNode *temp = root->left;
free(root);
return temp;
}
//该节点有两个子节点,找到后继节点并替换
TreeNode *temp = root->right;
while (temp->left != NULL) {
temp = temp->left;
}
root->value = temp->value;
root->right = deleteNode(root->right, temp->value);
}
return root;
}
//前序遍历二叉树
void preOrder(TreeNode *root) {
if (root != NULL) {
printf("%d ", root->value);
preOrder(root->left);
preOrder(root->right);
}
}
//测试
int main() {
TreeNode *root = initBinaryTree();
root = insertNode(root, 8);
root = insertNode(root, 3);
root = insertNode(root, 10);
root = insertNode(root, 1);
root = insertNode(root, 4);
root = insertNode(root, 9);
root = insertNode(root, 14);
preOrder(root);
printf("\n");
root = deleteNode(root, 8);
preOrder(root);
printf("\n");
return 0;
}
阅读全文