二叉树遍历模板


以下是复习默写记录的模板,为以后回顾模板方便

结构化定义

typedef struct node{
	elemType data;  //数据域 
	struct node *lchild, *rchild;  //左右孩子指针 
}Btree;

递归遍历

递归先序遍历

//递归先序遍历
void PreOrder(Btree T){
	visit(T);
	preOrder(T->lchild);
	preOrder(T->rchild);
}

递归中序遍历

//递归中序遍历
void InOrder(Btree T){
	InOrder(T->lchild);
	visit(T);
	InOrder(T->rchild);
}

递归后序遍历

//递归后序遍历
void PostOrder(Btree T){
	PostOrder(T->lchild);
	PostOrder(T->rchild);
	visit(T);
} 

非递归遍历

非递归先序遍历

//非递归先序遍历
void PreOrder(Btree T){
	InitStack(S); Btree p = T;
	while(p || !IsEmpty(S)){
		if(p){
			visit(p);
			push(S, p);
			p = p->lchild;
		}
		else{
			pop(S,p);
			p = p->rchild;
		}
	}
} 

非递归中序遍历

// 非递归中序遍历
void InOrder(Btree T){
	InitStack(S); Btree p = T;
	while(p || !IsEmpty(S)){
		if(p){
			push(S, p);
			p = p->lchild;
		}
		else {
			pop(S, p);
			visit(p);
			p = p->rchild;
		}
	}
} 

非递归后序遍历

// 非递归后续遍历
void PostOrder(Btree T){
	InitStack(S);  Btree p = T, b = NULL;
	
	while(p || !IsEmpty(S)){
		if(p){
			Push(S, p);
			p = p->lchild;
		} 
		else {
			GetTop(S, p);
			if(p->rchild && p->rchild!=r){
				p = p->rchild;
				Push(S, p);
				p = p->lchild;
			}
			else{
				Pop(S, p);
				visit(p);
				b = p;
				p = NULL;
			}
		}
	}
} 

层次遍历

//层次遍历
void levelOrder(Btree T){
	InitQueue(Q);
	Btree p;
	EnQueue(Q, T);
	while(!IsEmpty(Q)){
		DeQueue(Q, p);
		visit(p);
		if(p->lchild != null){
			EnQueue(Q, p->lchild);
		}
		if(p->rchild != null){
			EnQueue(Q, p->rchild);
		}
		
	}
} 
(p->lchild != null){
			EnQueue(Q, p->lchild);
		}
		if(p->rchild != null){
			EnQueue(Q, p->rchild);
		}
		
	}
} 
发布了63 篇原创文章 · 获赞 8 · 访问量 7181

猜你喜欢

转载自blog.csdn.net/s1547156325/article/details/105272318