概念
相关代码
main.c
#include"tree.h"
int main()
{
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
tree* root = CreateTree(arr, 10);
PreOrder(root);
putchar(10);
MidOrder(root);
putchar(10);
PostOrder(root);
putchar(10);
srand(time(NULL));
int num = 0;
tree* root1 = NULL;
for (int i = 0; i < 10; i++)
{
num = rand() % 100;
root1 = BsTreeInsert(root1, num);
}
MidOrder(root1);
return 0;
}
.c
#include"tree.h"
//创建
tree* CreateTree(int* p, int length)
{
tree * q[11] = {NULL};
for (int i = 0; i < length; i++)
{
//先创建10个节点
tree* temp = (tree*)malloc(sizeof(tree));
if (temp == NULL)
{
printf("malloc failure!\n");
return;
}
temp->data = p[i];
temp->left = NULL;
temp->right = NULL;
q[i] = temp;
}
//连起来
for (int i = 0; i < length / 2; i++)
{
q[i]->left = q[2 * i + 1];
q[i]->right = q[2 * i + 2];
}
return q[0];
}
//先序遍历
void PreOrder(tree* root)
{
if (NULL == root)//递归结束的条件
{
return;
}
printf("%d", root->data);
PreOrder(root->left);
PreOrder(root->right);
}
//中序遍历
void MidOrder(tree* root)
{
if (NULL == root)//递归结束的条件
{
return;
}
MidOrder(root->left);
printf("%d ", root->data);
MidOrder(root->right);
}
//后序遍历
void PostOrder(tree* root)
{
if (NULL == root)//递归结束的条件
{
return;
}
PostOrder(root->left);
PostOrder(root->right);
printf("%d", root->data);
}
//二叉搜索树
tree* BsTreeInsert(tree* root, Datatype num)
{
if (root == NULL)
{
root = (tree*)malloc(sizeof(tree));
if (root == NULL)
{
printf("malloc failure");
return;
}
//赋初值
root->data = num;
root->left = NULL;
root->right = NULL;
}
else
{
if (num < root->data)
{
root->left = BsTreeInsert(root->left, num);
}
else
{
root->right = BsTreeInsert(root->right, num);
}
}
return root;
}
//二叉树删除元素
tree* FindMinNum(tree* root)//找到右侧最小节点
{
while (root != NULL && root->left != NULL)
{
root = root->left;
}
return root;
}
//二叉树的删除
tree* BsTreeDelete(tree* root, Datatype data)
{
if (root == NULL)
{
printf("元素不存在!\n");
return NULL;
}
//找到要被删除的元素
if (data < root->data)
{
root->left = BsTreeDelete(root->left, data);
}
else if (data > root->data)
{
root->right = BsTreeDelete(root->right, data);
}
else//找到要被删除的元素
{
if (root->left == NULL)//说明最多只要一个右节点
{
tree* temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)//说明最多只要一个右节点
{
tree* temp = root->left;
free(root);
return temp;
}
else//左右节点都在
{
tree* temp = FindMinNum(root->right);
root->data = temp->data;
root->right = BsTreeDelete(root->right, temp->data);
}
}
}
.h
#pragma once
#ifndef _BSTREE_H_
#define _BSTREE_H_
#include<stdio.h>
#include<stdlib.h>
typedef int Datatype;
typedef struct node
{
struct node* left;
struct node* right;
Datatype data;
} tree;
//创建
tree* CreateTree(int* p, int length);
//先序遍历
void PreOrder(tree* root);
//中序遍历
void MidOrder(tree* root);
//后序遍历
void PostOrder(tree* root);
//二叉搜索树
tree* BsTreeInsert(tree* root, Datatype num);
#endif // !_BSTREE_H_