#include <stdio.h>
#include "myhd.h"
// 定义二叉树节点结构体
struct Tree
{
int value;
struct Tree *right;
struct Tree *left;
};
// 创建新节点
struct Tree *create_node(int value)
{
struct Tree *new = (struct Tree *)malloc(sizeof(struct Tree));
new->left = NULL;
new->right = NULL;
new->value=value;
return new;
};
// 创建二叉树
struct Tree *create_tree()
{
/* data */
// 创建根节点,编号为1
struct Tree *root = create_node(1);
// 创建根节点的做孩子节点,编号2
root->left = create_node(2);
root->right = create_node(3);
root->left->left = create_node(4);
root->right->right = create_node(5);
return root;
};
// 先序遍历
void first_output(struct Tree *node)
{
if (node != NULL)
{
printf("%d", node->value);
first_output(node->left);
first_output(node->right);
}
}
// 中序遍历
void mid_output(struct Tree *node)
{
if (node != NULL)
{
mid_output(node->left);
printf("%d", node->value);
mid_output(node->right);
}
}
// 二叉树后序遍历
void last_output(struct Tree *node)
{
if (node != NULL)
{
last_output(node->left);
last_output(node->right);
printf("%d", node->value);
}
}
// 二叉树的释放
void destry_space(struct Tree *node)
{
if (node != NULL)
{
destry_space(node->left);
destry_space(node->right);
free(node);
node = NULL;
}
};
int main(int argc, const char *argv[])
{
struct Tree *root = create_tree();
printf("first\n");
first_output(root);
printf("mid\n");
mid_output(root);
printf("last\n");
last_output(root);
putchar(10);
destry_space(root);
return 0;
}
2.4创建二叉树,并且实现三种遍历方式并且销毁
最新推荐文章于 2024-11-05 21:58:11 发布