The following uses C language to define a binary tree, and uses functions to achieve the following functions:
{
- Create a binary tree containing several nodes, when the value of the input node is -1, no longer create a binary tree;
- Realize the preorder traversal operation on the binary tree;
- Realize the in-order traversal operation on the binary tree;
- Implement the post-order traversal operation on the binary tree;
}
Students who are learning the data structure of c language are best not to copy it. It is the most important thing to write their own code through annotations.
Not much to say, directly on the code:
#include<stdio.h>
typedef struct tree{
int data;//节点数据
struct tree* rchild;//右子树
struct tree* lchild;//左子树
}treenode;//为结构体取别名
/******创建二叉树的节点******/
treenode* createnode(int x) {
int data,a;
treenode* node = (treenode *)malloc(sizeof(treenode));
scanf("%d", &data);//输入数据
a = getchar();//吸收多余的空格
if (data == -1)//输入-1代表节点下的子树不存数据,也就是不继续递归创建
return NULL;
node->data = data;//将输入的数值保存至节点
printf("请输入%d的左子树:", data);
node->lchild = createnode(data);//通过反复调用自身函数,达到循环子函数的目的
printf("请输入%d的右子树:", data);
node->rchild = createnode(data);
return node;
}
/******前序遍历******/
void prevorder(treenode* root) {
//接收主函数发来的地址
if (root == NULL) {
printf("#");//当前节点为空时打印#并返回
return;
}
printf("[%d]", root->data);//打印当前节点
prevorder(root->lchild);//遍历当前节点左子树
prevorder(root->rchild);//遍历当前节点右子树
}
/******中序遍历******/
void middleorder(treenode* root) {
if (root == NULL) {
printf("#");
return;
}
middleorder(root->lchild);//遍历左子树
printf("[%d]", root->data);//打印当前节点
middleorder(root->rchild);//遍历右子树
}
//后序遍历
void lastorder(treenode* root) {
if (root == NULL) {
printf("#");
return;
}
middleorder(root->lchild);//遍历左子树
middleorder(root->rchild);//遍历右子树
printf("[%d]", root->data);//打印当前节点
}
int main() {
int num;
treenode* root= (treenode *)malloc(sizeof(treenode));
while (1)
{
printf("\t提示:在输入信息后系统将自动初始化二叉树\n\n");
printf("\t\t1.创建二叉树\n\n");
printf("\t\t2.二叉树的前序遍历操作\n\n");
printf("\t\t3.二叉树的中序遍历操作\n\n");
printf("\t\t4.二叉树的后序遍历操作\n\n");
A: printf("*********************\n请选择功能项,并按回车执行:");
scanf("%d", &num);
switch (num)
{
/******创建二叉树******/
case 1:
{
printf("请输入需要创建根节点数据(输入-1代表不创建该位置子树,为空):");
root=createnode(0);
printf("\n二叉树创建完毕!\n");
goto A;//跳转至选项菜单
}
/******前序遍历******/
case 2:
{
printf("\n前序遍历完成(#为空子树):");
prevorder(root);
printf("\n");
goto A;
}
/******中序遍历******/
case 3:
{
printf("\n中序遍历完成(#为空子树):");
middleorder(root);
printf("\n");
goto A;
}
/******后序遍历******/
case 4:
{
printf("\n后序遍历完成(#为空子树):");
lastorder(root);
printf("\n");
goto A;
}
}
}
}