數據結構-樹-二叉樹-定義,遍歷

//定義
//二叉鏈表
typedef struct btnode
{
	DataType data;
	struct btnode *lchild,*rchild;
}*BinTree;
BinTree root;
//三叉鏈表
typedef struct ttnode
{
	DataType data;
	struct ttnode *lchild,*parent,*rchild;
}*TBinTree;
TBinTree root;

//遍歷
//先序
void preorder(BinTree bt)
{
	if (bt!=NULL)
	{
		visit(bt);
		preorder(bt->lchild);
		preorder(bt->rchild);
	}
}
//中序
void inorder (BinTree bt)
{
	if(bt!=NULL)
	{
		inorder(bt->lchild);
		visit(bt);
		inorder(bt->rchild);
	}
}
//後序
void postorder(BinTree bt)
{
	if (bt!=NULL)
	{
		postorder(bt->lchild);
		postorder(bt->rchild);
		visit(bt);
	}
}
//求深度
int Height(BinTree bt)
{
	int lh,rt;
	if (bt==NULL)
		return 0;
	else
	{
		lh=height(bt->lchild);
		rh=Height(bt->rchild);
		return 1+(lh>rh ? lh:rh);
	}
}
//層次遍歷
void levelorder(BinTree bt)
{
	LkQue Q;
	InitQueue(&Q);
	if (bt!=NULL)
	{
		EnQueue(&Q,bt);
		while (!EmptyQueue(Q))
		{
			p=Gethead(&Q);
			outQueue(&Q);
			visit(p);
			if(p->lchild!=NULL)
				EnQueue(&Q,p->lchild);
			if(p->rchild!=NULL)
				EnQueue(&Q,p->rchild);
		}
	}
}


//遍歷-非遞歸,中序visit調到pop(LS)和p=p->rchild之間
void PreOrder(BinTree t)
{
	BinTree p;
	LkStk *LS;
	if (t==NULL)
		return;
	InitStack (LS);
	p=t;
	while(p!=NULL||!EmptyStack(LS))
	{
		if (p!=NULL)
		{
			visit(p->data);
			Push(LS,p);
			p=p->lchild
		}
		else
		{
			p=GetTop(LS);
			Pop(LS);
			p=p->rchild
		}
	}
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章