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

📄 tree.h

📁 大三计算机的数据结构的 c++ 所用的 头文件
💻 H
字号:
#include <iostream.h>
#include <malloc.h>
#define MaxSize 100
#define Max Width 40
#define NULL 0
typedef char elemtype;
typedef struct node
{
	elemtype data;
	struct node *left,*right;
}BTree;
void creatree(BTree *&b,char *str)
//其中str为用广义表的形式描述二叉树如a(b,c),表示以a为根,b和c为a的左右子树根,
//则用creatree(x,"a(b,c)" 来建立这棵树
//a(,c)表示a只有右子树c,没有左子树,注意","不能少
//例如构造这样一棵树,a为根结点,左右子树分别为b,c,d为b的右子树,e为c的左子树,
//则用creatree(x,"a(b(,d),c(e,))",其中x为用BTree *x定义。
{
	BTree *stack[MaxSize],*p;
	int top=-1,k,j=0;
	char ch;
    b=NULL;
	ch=str[j];
	while(ch!='\0')
	{
		switch(ch)
		{
		case '(':top++;stack[top]=p;k=1;break;
		case ')':top--;break;
		case ',':k=2;break;
		default:p=(BTree *)malloc(sizeof(BTree));
			p->data=ch; p->left=p->right=NULL;
			if (b==NULL)  b=p;
			else
			{
				switch(k)
				{
				  case 1:stack[top]->left=p;break;
				  case 2:stack[top]->right=p;break;
				}
			}
		}
		j++;
		ch=str[j];
	}
}

void preorder(BTree *b)
//先序遍历二叉树
{
	if(b!=NULL)
	{
		cout<<b->data<<" ";
		preorder(b->left);
		preorder(b->right);
	}
}

void inorder(BTree *b)
//中序遍历二叉树
{
	if(b!=NULL)
	{
		inorder(b->left);
		cout<<b->data<<" ";
		inorder(b->right);
	}
}

void postorder(BTree *b)
//后序遍历二叉树
{
	if(b!=NULL)
	{
		postorder(b->left);
		postorder(b->right);
		cout<<b->data<<" ";
	}
}

void printree(BTree *b)
//用广义表的格式输出二叉树
{
	if(b!=NULL)
	{
		cout<<b->data;
		if(b->left!=NULL || b->right!=NULL)
		{
			cout<<"(";
			printree(b->left);
			if(b->right!=NULL) cout<<",";
			printree(b->right);
			cout<<")";
		}
	}
}

⌨️ 快捷键说明

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