二叉树的建立和应用

本文介绍了一种基于前序遍历创建二叉树的方法,并实现了递归与非递归方式下的前序、中序及后序遍历。通过具体的代码示例,详细展示了二叉树的构建过程及其遍历算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本人数据结构实验课写出来的垃圾代码。仅供参考。

树的应用 

1、实验目的

通过本实验掌握二叉的建立和递归遍历、非递归遍历算法,了解二叉树在实际中的应用并熟练运用二叉树解决实际问题。

2、实验内容

根据前序遍历的顺序建立一棵二叉树,并根据遍历规则遍历二叉树。并打印输出。

3、实验要求

(1)根据前序遍历的顺序创建一棵二叉树;

(2)对二叉树进行前序、中序、后序遍历。

代码:

#include"stdio.h"
#include"stdlib.h"
	typedef struct bintnode{
		char data;
		struct bintnode *lchild,*rchild;
	}node;//樹結構 
	
	typedef node *binepoint;
	
	typedef struct seqstack{
		binepoint data[100];
		int tag[100];
		int top;
	}stack;//棧結構 
	
	void push(stack *s,binepoint t)
	{
		s->data[s->top]=t;
		s->top++;
	}//壓棧函數 
	
	binepoint pop(stack *s)
	{
		if(s->top!=0)
		{
			s->top--;
			return (s->data[s->top]);
			}
		else return NULL;
		}//出棧函數 
	
int main()
{
	binepoint createtree();
	void preorder(binepoint t);
	void inorder(binepoint t);
	void postorder(binepoint t);
	void preorder1(binepoint t);
	void inorder1(binepoint t);
	void postorder1(binepoint t);
	
	node *root;
	root=createtree();
	
	printf("首先。這個是前序遍曆\n");
	preorder(root);
	putchar('\n');
	preorder1(root);
	putchar('\n');
	printf("第二。我們要進行中序遍歷\n");
	inorder(root);
	putchar('\n'); 
	inorder1(root);
	putchar('\n'); 
	printf("最後,我們要進行後序遍曆\n");
	postorder(root); 
	putchar('\n');
	postorder(root);
	putchar('\n'); 
	return 0;
 }	
    binepoint createtree()
    {
		char ch;
		binepoint t;
		if ((ch=getchar())=='#') t=NULL;
		else {
			t=(node*)malloc(sizeof(node));
			t->data=ch;
			t->lchild=createtree();
			t->rchild=createtree();
		}
			return t;
	}

void preorder(binepoint t)
{
	stack s;
	s.top=0;
	while((t||(s.top!=0)))
	{
		if(t)
		{
			printf("%c",t->data);
		push(&s,t);
		t=t->lchild;
		}
		else 
		{
			t=pop(&s);
			t=t->rchild;
		}
	}
	
}
void inorder(binepoint t)
{
	stack s;
	s.top=0;
	while((t!=NULL)||(s.top!=0))
	{
		if(t)
		{
			push(&s,t);
			t=t->lchild;
		}
		else 
		{
			t=pop(&s);
			printf("%c",t->data);
			t=t->rchild;						
		}
	}
}
void postorder(binepoint t)
{
	stack s;
	s.top=0;
	while((t)||(s.top!=0))
	{
		if(t)
		{
		s.data[s.top]=t;
		s.tag[s.top]=0;
		s.top++;
		t=t->lchild;		
		}
		else if(s.tag[s.top-1]==1)
		{	
				s.top--;
				t=s.data[s.top];
				printf("%c",t->data);
				t=NULL;
		}
		else
		{
			t=s.data[s.top-1];
			s.tag[s.top-1]=1;
			t=t->rchild;
		}
 	}
 }
void preorder1(binepoint t)
{
	if (t)
	{	
		printf("%c",t->data);
		preorder1(t->lchild);
		preorder1(t->rchild);
	}
}
void inorder1(binepoint t)
{
	if(t)
	{
		inorder1(t->lchild);
		printf("%c",t->data);
		inorder1(t->rchild);
	}
}

void postorder1(binepoint t)
{
	if(t)
	{
		postorder1(t->lchild);
		postorder1(t->rchild);
		printf("%c",t->data);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值