这个很容易想到
层次遍历是自上而下,从左到右,
说明将层次遍历出队列的元素入栈,最后出栈即可得
b本篇以根节点为8的二叉搜索树8、5、10、3、7、9、11为例

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

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

typedef struct Q {
	Btree *P3;
	struct Q*next;
}Array;                             //队列

Btree *insert(Btree*Ntree, int a);//插入节点
void Push(Node**top, Btree*P2);   //压入栈
void Pop(Node**top);              //出栈
void Push2(Array**q, Btree*P);    //入队列
void Pop2(Array**head);           //出队列
void BLorder(Btree* Ntree) ;      //如题遍历
int main() {
	int a;
	Btree *Ntree;
	Ntree = (Btree*)malloc(sizeof(struct Tree));
	Ntree->Data=8;
	Ntree->Lc = Ntree->Rc = NULL;
	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);
}

void Push2(Array**q, Btree*P){
	Array*N;
	N = (Array*)malloc(sizeof(struct Q));
	N->P3 = P;
	N->next = NULL;
	(*q)->next = N;
	*q = N;
}
void Pop2(Array**head) {
	Array*N;
	N = (Array*)malloc(sizeof(struct Q));
	N = (*head);
	(*head)= N->next;
	free(N);
}
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 BLorder(Btree* Ntree) {
	Btree *P;
	P = Ntree;//用P来遍历
	Array *head;//队列的头节点
	head = (Array *)malloc(sizeof(struct Q));
	head->next = NULL;
	Array *tail;//队列的尾节点
	tail = head;
	Nodes*N;
	N = (Nodes*)malloc(sizeof(struct Node));
	N = NULL;
	Nodes*top;//指向栈顶元素
	top = N;
	Push2(&tail, P); //将根节点入队列
	while (head->next) { //当队列空时停止循环
		Push(&top, head->next->P3);//将队列的头元素入栈
		Pop2(&head);               //将队列的头元素出队列
		if (P->Lc)
			Push2(&tail, P->Lc);
		if (P->Rc)
			Push2(&tail, P->Rc);
		if (head->next)
			P = head->next->P3;    //使P指向队列的头节点
	}
	while (top) {   
		printf("%d\n", top->P1->Data);
		Pop(&top);
	}
}
Logo

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

更多推荐