#include <stdio.h>
#include<stdlib.h>
//实现排序二叉树的构造,四种遍历
typedef struct node {
int data;
node* left;
node* right;
} Node;
typedef struct {
Node* root;
} Tree;
void Insert(Tree* t, int value) {
Node* node = (Node*)malloc(sizeof(Node));
if (node == NULL)
{
return;
}
node->data = value;
node->left = NULL;
node->right = NULL;
if (t->root == NULL)
{
t->root = node;
}
else
{
Node* temp = t->root;
while (temp != NULL)
{
if (value < temp->data)
{
if (temp->left == NULL)
{
temp->left = node;
return;
}
else
{
temp = temp->left;
}
}
else
{
if (temp->right == NULL)
{
temp->right = node;
return;
}
else
{
temp = temp->right;
}
}
}
}
}
void PreOrder(Node* n) {
if (n != NULL)
{
printf("%d ", n->data);
PreOrder(n->left);
PreOrder(n->right);
}
}
void InOrder(Node* n) {
if (n != NULL)
{
InOrder(n->left);
printf("%d ", n->data);
InOrder(n->right);
}
}
void PostOrder(Node* n) {
if (n != NULL)
{
PostOrder(n->left);
PostOrder(n->right);
printf("%d ", n->data);
}
}
//链队列结点定义
typedef struct qnode {
Node* node;
qnode* next;
}QNode;
//链队列
typedef struct {
QNode* front;
QNode* rear;
}Queue;
//无头结点的链队列初始化
void InitQ(Queue& q) {
q.front = NULL;
q.rear = NULL;
}
//入队
void EnQueue(Queue& q, Node* node) {
QNode* new_node = (QNode*)malloc(sizeof(QNode));
if (new_node == NULL)
{
return;
}
new_node->node = node;
new_node->next = NULL;
if (q.front==NULL && q.rear==NULL)
{
q.front = new_node;
q.rear = new_node;
}
else
{
q.rear->next = new_node;
q.rear = new_node;
}
}
//出队 注意Node**node这里
void DeQueue(Queue& q, Node* *node) {
if (q.front == NULL)
{
return;
}
QNode* denode = q.front;
*node = denode->node;
//针对最后一个结点出队这里需要特殊处理 这里卡了一下 开始没有考虑到
if (denode->next==NULL)
{
q.front = NULL;
q.rear = NULL;
}
else
{
q.front = denode->next;
}
free(denode);
}
void LevelOrder(Node* n) {
Queue q;
InitQ(q);
EnQueue(q, n);
Node* temp = (Node*)malloc(sizeof(Node));
while (q.front != NULL)
{
DeQueue(q, &temp);
printf("%d ", temp->data);
if (temp->left != NULL)
{
EnQueue(q, temp->left);
}
if (temp->right != NULL)
{
EnQueue(q, temp->right);
}
}
printf("\n");
}
int main() {
Tree t;
t.root = NULL;
int arr[8] = { 7,4,8,6,5,3,9,1 };
for (int i = 0; i < 8; i++)
{
Insert(&t, arr[i]);
}
printf("\n先序遍历:");
PreOrder(t.root);
printf("\n中序遍历:");
InOrder(t.root);
printf("\n后序遍历:");
PostOrder(t.root);
printf("\n层次遍历:");
LevelOrder(t.root);
}
二叉排序树的构造和四种遍历的C实现
于 2022-09-08 16:33:08 首次发布