二叉树的操作


包含根据广义表来创建二叉树,显示二叉树,先、中、后序访问二叉树


#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define ElemType char
#define uint unsigned int
#define N 100

typedef struct tree
{
	ElemType data;
	struct tree *lchild,*rchild;
}TreeNode;

TreeNode *create( char tree[]);
void showtree(TreeNode *);
void preorder(TreeNode *head);
void inorder(TreeNode *head);
void postorder(TreeNode *head);

int main()
{
	TreeNode *head;
	char tree[100]="A(B(M,N),C(E))";
	//printf("input the string\n");
	//scanf("%s",tree);
	head=NULL;
	head=create(tree);
	showtree(head);
	printf("\n");
	preorder(head);
	printf("\n");
	inorder(head);
	postorder(head);
	return 0;
}
TreeNode *create( char tree[])    //新建树 
{
	uint i=0,len;
	int flag=0,top=-1;
	len=strlen(tree);
	TreeNode *p,*st[N];
	for(i=0;i<len;i++)
	{
		switch(tree[i])
		{
		case '(': top++; st[top]=p; flag=1;break;
		case ',': flag=2; break;
		case ')': top--; break;
		default:
			p=(TreeNode *)malloc(sizeof(TreeNode));
			p->data=tree[i];
			p->lchild=p->rchild=NULL;
			if(top==-1)
			{
				top++;
				st[top]=p;
			}
			else
			{
				switch(flag)
				{
				case 1: st[top]->lchild=p; break;
				case 2: st[top]->rchild=p; break;
				}
			}
		}
		 
	}
	return st[0];
}
void showtree(TreeNode *head)   //显示树
{
	if(head!=NULL)
	{
		printf("%c",head->data);
		if(head->lchild!=NULL || head->rchild!=NULL)
		{
			printf("(");
			showtree(head->lchild);
			if(head->rchild!=NULL)
				printf(",");
			showtree(head->rchild);
			printf(")");
		}
	}

}
void preorder(TreeNode *head)  //先序非递归遍历
{
	TreeNode *st[N],*p=head;
	int top=-1;
	if(head!=NULL)
	{
		top++;
		st[top]=head;
		while(top>-1)
		{
			p=st[top];
			top--;
			printf("%c",p->data);
			if(p->rchild!=NULL)
			{
				top++;
				st[top]=p->rchild;
			}
			if(p->lchild!=NULL)
			{
				top++;
				st[top]=p->lchild;
			}
		}
	}
}
void inorder(TreeNode *head)  //中序非递归遍历
{
	TreeNode *p,*st[N];
	int top=-1;
	if(head!=NULL)
	{
		p=head;
		while(top>-1 || p!=NULL)
		{
			while(p!=NULL)
			{
				top++;
				st[top]=p;
				p=p->lchild;
			}
			if(top>-1)
			{
		     	printf("%c",st[top]->data);
				p=st[top]->rchild;
				top--;		
			}
		}
	}
	printf("\n");
}
void postorder(TreeNode *head)  //后序非递归遍历
{
	TreeNode *p,*st[N];
	int top=-1;
	if(head!=NULL)
	{
		top++;
		st[top]=head;
		do
		{
			p=NULL;
			while(st[top]->lchild!=NULL)
			{
				st[top+1]=st[top]->lchild;
				top++;
			}
		}while(top>-1);
	}
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值