[DS]二叉树的非递归先序、后序、中序遍历

先序遍历

1.当前节点非空,则打印之再压栈
2.当前节点空,则退栈,遍历节点 = 退出来栈的节点的右孩子

中序遍历

1.如果该节点左孩子非空,则左孩子压栈
2.如果左孩子为空,则退栈,打印当前节点,遍历节点 = 退出来的右孩子
3.当指针为空并且栈空时,结束while

后序遍历

1.先边压栈边走到最左边
2.如果左孩子空了,getTop(就是从空的左孩子往上退),看右孩子:
2.1如果右孩子空,就退栈,(指针还是原来的,但是退栈了),现在的节点是recent point(以防他是某人的右孩子),遍历指针 = NULL(以便下次循环往上退)
2.2如果右孩子被记录过了,处理与2.1一样
2.3如果右孩子没空且没记录过,就令当前节点=右孩子

代码:

#include 
#include 

typedef struct Node{
	int data;
	struct Node *l,*r;
}Node,*Tree;

typedef struct stack{
	struct Node* point;
	struct stack *next;
}stack,*Linkstack;

void push(Linkstack &S,Tree p){
	stack *s = (stack*)malloc(sizeof(stack));
	s->point = p;
	s->next = S->next;
	S->next = s;
}

void pop(Linkstack &S,Tree &p){
	p = S->next->point;
	S->next = S->next->next;
}

void pre_order(Tree T){
	if(T!=NULL){
		printf("%d ",T->data);
		pre_order(T->l);
		pre_order(T->r);
	}
}

void inorder_nonrecursion(Tree T){
	Linkstack S = (stack*)malloc(sizeof(stack));
	S->next = NULL;
	Node *p = T;
	while(p||S->next!=NULL){
		if(p){
			push(S,p);
			p = p->l;
		}else{
			if(S->next!=NULL){
				pop(S,p);
				printf("%d ",p->data);
				p = p->r;
			}
		}
	}
}

void preorder_nonrecursion(Tree T){
	Linkstack S = (stack*)malloc(sizeof(stack));
	S->next = NULL;
	
	Node *p = T;
	while(p||S->next!=NULL){
		if(p){
			printf("%d ",p->data);
			push(S,p);
			p = p->l;
		}else{
			pop(S,p);
			p = p->r;
		}
	}
}

void getTop(Linkstack S,Tree &p){
	p = S->next->point;
}

void postorder_nonrecursion(Tree T){
	Linkstack S = (stack*)malloc(sizeof(stack));
	S->next = NULL;
	Node *p = T;
	Node *k = NULL; //record the point visted recently
	while(p||S->next!=NULL){
		if(p){
			push(S,p);
			p = p->l;
		}else{
			getTop(S,p);
			if(p->r&&k!=p->r){
			//when right child is not NULL and never be visited
				p = p->r;
			}else{
				pop(S,p);
				printf("%d ",p->data);
				k = p;    //current p might be other's right child
				p = NULL; //use this way to pop again
			}
		}
	}
}

Tree create(){
	int _input;
	scanf("%d",&_input);
	if(_input == 0){
		return NULL;
	}else{
		Node *N = (Node*)malloc(sizeof(Node));
		N->data = _input;
		N->l = create();
		N->r = create();
		return N;
	}
}

int main(){
	Tree T = (Node*)malloc(sizeof(Node));
	printf("enter the head point");
	scanf("%d",&T->data);
	T->l = create();
	T->r = create();
	
	//pre_order(T);
	//preorder_nonrecursion(T);
	postorder_nonrecursion(T);
	
	return 0;
}

你可能感兴趣的:(数据结构,c++,数据结构,链表)