⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 5.cpp

📁 二叉树的创建
💻 CPP
字号:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
typedef char datatype;
#define maxsize 50
typedef struct node{
	datatype data[10];
	struct node*lchild;
	struct node*rchild;
}bitree;
bitree*creat_bitree(bitree *rt)//创建一个二叉树(前序)
{
	char ch[10];
	int i=0;
	scanf("%s",ch);
	if(ch[0]=='0')
		rt=NULL;
	else
	{

		rt=(bitree*)malloc(sizeof(bitree));
		strcpy(rt->data,ch);
		rt->lchild=creat_bitree(rt->lchild);
		rt->rchild=creat_bitree(rt->rchild);
		
	}

		return rt;
}
void preorder (bitree* root)//前序遍历
{ 
	if(root!=NULL)
	{   
       
        printf("%10s",root->data);
		preorder(root->lchild);
		preorder(root->rchild);
	}
}
void inorder (bitree* root)//中序遍历
{ 
	if(root!=NULL)
	{   
       preorder(root->lchild);
		printf("%10s",root->data);
		preorder(root->rchild);
	}
}
void postorder (bitree* root)//后序遍历
{ 
	if(root!=NULL)
	{   
       preorder(root->lchild);
		preorder(root->rchild);
		printf("%10s",root->data);
	}
}
int countnode(bitree*root)
{   
     static int count=0;
   
	if(root!=NULL)
	{
		count++;
        countnode(root->lchild);
		countnode(root->rchild)	;
	
	}
		return count;
}
void main()
{   
   
	bitree*head=NULL,*p;
	int r;
	int x;
	printf("请输入二叉树的节点的内容:\n");
	p=creat_bitree(head);
	printf("********************************\n");
	printf("0                    前序遍历二叉树\n");
	printf("1                    中序遍历二叉树\n");
	printf("2                    后序遍历二叉树 \n");
	printf("3                    求节点的个数\n");
    printf("********************************\n");
	printf("请输入选项(0-3):\n");
	scanf("%d",&x);
	switch(x)
	{
	case 0:preorder(p);break;
	case 1: inorder (p);break;
    case 2:postorder (p);break;
    case 3:
		{
    printf("节点数为\n");
    r=countnode(p);
	printf("%d\n",r);
		}break;

	}
}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -