用C语言写一段代码,二叉树节点是char类型,实现二叉树节点的删除操作。具体过程为根据输入的节点创建二叉树,再次输入一个二叉树中某个节点的值,在二叉树中找到该节点,删除该节点的左子树
时间: 2023-10-10 11:04:29 浏览: 77
以下是一份C语言实现二叉树节点删除操作的代码,其中二叉树节点是char类型:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
char data;
struct Node *left;
struct Node *right;
} Node;
Node *createNode(char data) {
Node *newNode = (Node *) malloc(sizeof(Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
Node *insertNode(Node *root, char data) {
if (root == NULL) {
return createNode(data);
} else if (data <= root->data) {
root->left = insertNode(root->left, data);
} else {
root->right = insertNode(root->right, data);
}
return root;
}
Node *findNode(Node *root, char data) {
if (root == NULL || root->data == data) {
return root;
} else if (data < root->data) {
return findNode(root->left, data);
} else {
return findNode(root->right, data);
}
}
Node *deleteNode(Node *root, char data) {
if (root == NULL) {
return root;
} else if (data < root->data) {
root->left = deleteNode(root->left, data);
} else if (data > root->data) {
root->right = deleteNode(root->right, data);
} else {
if (root->left == NULL) {
Node *temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
Node *temp = root->left;
free(root);
return temp;
}
Node *temp = root->right;
while (temp->left != NULL) {
temp = temp->left;
}
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}
void inorderTraversal(Node *root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%c ", root->data);
inorderTraversal(root->right);
}
}
int main() {
Node *root = NULL;
root = insertNode(root, 'd');
root = insertNode(root, 'b');
root = insertNode(root, 'f');
root = insertNode(root, 'a');
root = insertNode(root, 'c');
root = insertNode(root, 'e');
root = insertNode(root, 'g');
printf("Inorder traversal of the original tree:\n");
inorderTraversal(root);
char dataToDelete;
printf("\nEnter the value of a node to delete its left subtree: ");
scanf(" %c", &dataToDelete);
Node *nodeToDelete = findNode(root, dataToDelete);
if (nodeToDelete != NULL) {
nodeToDelete->left = NULL;
printf("Inorder traversal of the modified tree:\n");
inorderTraversal(root);
} else {
printf("Node not found in the tree\n");
}
return 0;
}
```
在上面的代码中,我们首先定义了一个结构体Node来表示二叉树节点,包括数据data、左子树节点left和右子树节点right。接着,我们定义了一些函数来创建节点、插入节点、查找节点、删除节点和进行中序遍历操作。在main函数中,我们创建了一个二叉树并进行了中序遍历。然后,我们输入一个要删除其左子树的节点的值,在二叉树中查找该节点并删除其左子树。最后,我们再次进行中序遍历以查看修改后的二叉树。
阅读全文