用C语言写一段代码,二叉树节点是char类型,实现二叉树节点的删除操作,具体过程为根据输入的节点,在二叉树中找到该节点,删除该节点的左子树
时间: 2023-09-23 20:13:00 浏览: 75
c代码-二叉搜索树的删除操作
以下是用C语言实现二叉树节点删除操作的代码,具体过程为根据输入的节点,在二叉树中找到该节点,删除该节点的左子树:
```c
#include<stdio.h>
#include<stdlib.h>
struct node {
char data;
struct node *left;
struct node *right;
};
struct node *create_node(char value) {
struct node *new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = value;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
struct node *insert_node(struct node *root, char value) {
if(root==NULL) {
return create_node(value);
}
if(value < root->data) {
root->left = insert_node(root->left, value);
}
else {
root->right = insert_node(root->right, value);
}
return root;
}
struct node *find_node(struct node *root, char value) {
if(root==NULL || root->data==value) {
return root;
}
if(value < root->data) {
return find_node(root->left, value);
}
else {
return find_node(root->right, value);
}
}
struct node *delete_left_subtree(struct node *root, char value) {
struct node *node_to_delete = find_node(root, value);
if(node_to_delete!=NULL && node_to_delete->left!=NULL) {
node_to_delete->left = NULL;
}
return root;
}
void inorder_traversal(struct node *root) {
if(root!=NULL) {
inorder_traversal(root->left);
printf("%c ", root->data);
inorder_traversal(root->right);
}
}
int main() {
struct node *root = NULL;
root = insert_node(root, 'F');
root = insert_node(root, 'D');
root = insert_node(root, 'J');
root = insert_node(root, 'B');
root = insert_node(root, 'E');
root = insert_node(root, 'G');
root = insert_node(root, 'K');
root = insert_node(root, 'A');
root = insert_node(root, 'C');
root = insert_node(root, 'I');
root = insert_node(root, 'H');
printf("Inorder traversal before deleting left subtree of node D:\n");
inorder_traversal(root);
printf("\n");
root = delete_left_subtree(root, 'D');
printf("Inorder traversal after deleting left subtree of node D:\n");
inorder_traversal(root);
printf("\n");
return 0;
}
```
这段代码实现了二叉树节点的删除操作,具体过程为根据输入的节点,在二叉树中找到该节点,删除该节点的左子树。在这个例子中,我们创建了一个二叉树,并在其中插入了一些节点。然后打印出插入节点后的中序遍历结果。接着删除节点D的左子树,并再次打印出删除左子树后的中序遍历结果。
阅读全文