本篇用一棵根节点为8的二叉搜索树来遍历
8、5、10、3、7、9、11

#include<stdio.h>
#include<stdlib.h>
#pragma warning(disable:4996)

typedef struct Tree {
	int Data;
	struct Tree *Lc;
	struct Tree *Rc;
}Btree;         //一个树节点

typedef struct Node {
	Btree *P1;
	struct Node *rear;
}Nodes;         //栈

void Push(Node**top, Btree*P2) ;//进栈
void Pop(Node**top);            //出栈
Btree *insert(Btree*Ntree, int a);//插入节点
void Beorder(Btree* Ntree);       //后序遍历

int main() {
	int a;
	Btree *Ntree;
	Ntree = (Btree*)malloc(sizeof(struct Tree));
	Ntree->Data=8;
	Ntree->Lc = Ntree->Rc = NULL;//根节点是8
	for (int i = 0; i < 6; i++) {
		scanf("%d", &a);
		Ntree=insert(Ntree, a);//插入子节点
	}
	BLorder(Ntree);
	system("pause");
	return 0;
}
void Push(Node**top, Btree*P2) {
	Nodes*N;
	N = (Nodes*)malloc(sizeof(struct Node));
	N->P1 = (Btree*)malloc(sizeof(struct Tree));
	N->P1 = P2;
	N->rear =(*top);
	(*top)= N;
}

void Pop(Node**top) {
	Nodes*P;
	P = (Nodes*)malloc(sizeof(struct Node));
	P = *top;
	(*top) = (*top)->rear;
	free(P);
}

Btree *insert(Btree*Ntree, int a) {
	if (!Ntree) {
		Ntree = (Btree*)malloc(sizeof(struct Tree));
		Ntree->Data = a;
		Ntree->Lc = Ntree->Rc = NULL;
	}                                 //递归结束条件,创造一个新节点
	else if (a > Ntree->Data) {
			Ntree->Rc = insert(Ntree->Rc, a);
		}
	else if (a < Ntree->Data) {
			Ntree->Lc = insert(Ntree->Lc, a);
		}
	
	return Ntree;
}

void Beorder(Btree* Ntree) {
	Btree*P = Ntree;
	Nodes*top;
	top = NULL;
	Btree*r;                 //用于判断是否二次访问同一个节点
	r = NULL;
	while (P || top) {       //节点和栈不都等于空时循环继续
		if (P) {             //P不为空
			Push(&top, P);   //向左遍历将节点压入栈直到空节点
			P = P->Lc;      
		}
		else {                //P为空时
			P = top->P1;     //将P指向栈顶元素
			if (P->Rc&&P->Rc != r) {  //如果P节点的右子树不为空且只访问过P节点一次
				P = P->Rc;          //以P节点右子树为根节点向左遍历并压栈
				Push(&top, P);
				P = P->Lc;
			}
			else {               //当P的右子树为空或P被访问了2次
				printf("%d\n", top->P1->Data); //访问P元素
				Pop(&top);                     //将P元素出栈
				r = P;                         //使r指向最近访问的元素
				P = NULL;                      //重置P
			}
		}

	}
}
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐