數據結構 二叉樹常用簡單應用

#define MAX 100

typedef struct {
	datatype SqBiTree[Max+1];
	int nodemax;
}Bitree;
typedef struct {
	DataType data;
	Struct Node * Lchild;
	Struct Node * Rchild; 
}BiTNode,*BiTree;

1.先序遍歷

void preOrder(BiTree root){
	if(root){
		Visit(root->data);
		preOrder(root->Lchild);
		preOrder(root->Rchild);
	}
} 

2.中序遍歷

void InOrder(BiTree root){
	if(root){
		preOrder(root->Lchild);
		Visit(root->data);
		preOrder(root->Rchild);
	}
}
3.後序遍歷
void PostOrder(BiTree root){
	if(root){
		preOrder(root->Lchild);
		preOrder(root->Rchild);
		Visit(root->data);
	}
} 
4.先序非遞歸 

void PreOrder(BiTree root){
	SeqStack *s;Bitree p;
	InitStack(s);p = root;
	while(p != NULL){
		Visit (p->data);
		Push(s,p);
		p = p->Lchild;
	} 
	if(!IsEmpty(S)){
		Pop(s,&p);
		p= p->Rchild;
	}
}
5.中序非遞歸 

void InOrder(BiTree root){
	SeqStack *S;BiTree p;
	InitStack(S);p = root;
	while(p!=NULL || !IsEmpty(S)){
		while(p!=null){
			Push(S,p);
			p=p->Lchild;
		}
		if(!IsEmpty(S))
		{
			Pop(S,&p);
			Visit(p->data);
			p=p->Rchild;
		}
	}
}
6.後序非遞歸

void PostOrder(BiTree root){
	SeqStack *S;BiTree p,q;
	InitStack(S);p = root;q=null;
	while(p!=null || IsEmpty(S)){
		while(p!= null){
			Push(S,p);
			p = p->Lchild;
		}
		if(!IsEmpty(S)){
			Top(S,&p);
			
			p=p->Rchild;
	}	
} 
7.二叉樹層次遍歷

void LevelOrder(BiTree root){
	SeqQueue *Q;BiTree p;
	InitQueue(Q);EnterQueue(Q,root);
	while(!IsEmpty(Q)){
		DeleteQueue(Q,&p);
		Visit(p->data);
		if(p->Lchild!=null){
			EnterQueue(Q,p->Lchild);
		}
		if(p->Rchild!=null){
			EnterQueue(Q,p->Rchild);
		}
	}	
} 
8.先序遍歷統計結點 

void PreOrder(BiTree root){
	if(root){
		Count++;
		PreOrder(root->Lchild);
		PreOrder(root->Rchild);
	}
}
9.輸出葉子結點

void InOrder(BiTree root){
	if(root){
		InPreOrder(root->Lchild);
		if(root->Lchild == NULL && root ->Rchild==NULL){
			printf(root->data);
		}
		InOrder(root->Echild);
		
	}
} 
10.統計葉子結點數目

int leaf(BiTree root){
	int nl,nr;
	if(root == NULL)	return 0;
	if((root->Lchild==NULL) && (root->Rchild==NULL)	)	return 1;
	nl = leaf(root->Lchild);
	nr = leaf(root->Rchild);
	return (nl+nr);
} 
11.二叉樹高度

void TreeDepth(BiTree root,int h){
	if(root){
		if(h>depth)		depth = h;
		TreeDepth(root->Lchild,h+1);
		TreeDepth(root->Rchild,h+1);
	}
} 
12.按樹狀打印二叉樹

void PrintTree(BiTree root){
	if(root = Null)		return ;
	PrintTree(root->Rchild,h+1);
	int i=0;
	for(i=0;i<h;i++){
		Printf(" ");
	}
	printf("%c\n",root->data);
	PrintTree(root->Lchild,h+1);	
} 
























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