后序遍历非递归(作业
  hI6KHgNRyc1X 2023年11月05日 19 0
#define _CRT_SECURE_NO_WARNINGS
#define Max 64
#include<stdio.h>
#include<stdlib.h>


//二叉树的定义
typedef struct node
{
	char data;
	int visit;
	struct node* lchild;
	struct node* rchild;
}bitree;


//栈的定义
typedef struct
{
	bitree* data[Max];
	int top;
}seqstack;


//创建二叉树
bitree* CREATREE()
{
	bitree* Q[50];
	char ch;
	int front, rear;
	bitree* root, * s;
	root = NULL;//置空二叉树
	front = 1; rear = 0;
	ch = getchar();
	while (ch != '#')//#是结束字符
	{
		s = NULL;
		if (ch != '@')//@表示虚结点,不是虚结点建立新结点
		{
			s = (bitree*)malloc(sizeof(bitree));
			s->data = ch;
			s->lchild = NULL;
			s->rchild = NULL;
		}
		rear++;
		Q[rear] = s;//虚结点指针NULL或新结点地址入队
		if (rear == 1)
		{
			root = s;//输入的第一个结点为根结点
			s->visit = 0;
		}
		else
		{
			if (s && Q[front])//孩子和双亲都不是虚结点
			{
				if (rear % 2 == 0)
				{
					Q[front]->lchild = s;//rear为偶数,新结点是左孩子
					s->visit = 0;
				}
				else
				{
					Q[front]->rchild = s;//奇数是新结点是右孩子
					s->visit = 0;
				}
			}
			if (rear % 2 == 1)
				front++;//两个孩子均已处理完毕,出队列
		}
		ch = getchar();//输入下一个字符
	}
	return root;
}


//后序遍历非递归算法
void POSTORDER2(bitree* t)
{
	seqstack* s;
	s = (seqstack*)malloc(sizeof(seqstack));
	s->top = 0;
	s->data[s->top] = t;
	while (s->top != -1)
	{
		if (s->data[s->top]->lchild != NULL && s->data[s->top]->lchild->visit == 0)
		{
			s->data[s->top + 1] = s->data[s->top]->lchild;
			s->top++;
		}
		else if (s->data[s->top]->rchild != NULL && s->data[s->top]->rchild->visit == 0)
		{
			s->data[s->top + 1] = s->data[s->top]->rchild;
			s->top++;
		}
		else if (s->data[s->top]->visit == 0)
		{
			printf("%c ", s->data[s->top]->data);
			s->data[s->top]->visit = 1;
			s->top--;
		}
	}
}


//打印祖先
void Printfather(bitree* t,char x)
{
	seqstack* s;
	s = (seqstack*)malloc(sizeof(seqstack));
	s->top = 0;
	s->data[s->top] = t;
	while (s->top != -1)
	{
		if (s->data[s->top]->data == x)
		{
			//打印栈
			int tem = 0;
			tem = s->top;
			while (tem != 0)
			{
				printf("%c ", s->data[tem-1]->data);
				tem--;
			}
		}
		if (s->data[s->top]->lchild != NULL && s->data[s->top]->lchild->visit == 0)
		{
			s->data[s->top + 1] = s->data[s->top]->lchild;
			s->top++;
		}
		else if (s->data[s->top]->rchild != NULL && s->data[s->top]->rchild->visit == 0)
		{
			s->data[s->top + 1] = s->data[s->top]->rchild;
			s->top++;
		}
		else if (s->data[s->top]->visit == 0)
		{
			//printf("%c ", s->data[s->top]->data);
			s->data[s->top]->visit = 1;
			s->top--;
		}
	}
}


int main()
{
	bitree* t = CREATREE();
	Printfather(t, 'D');
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  L2jbKj3EiIPy   2023年12月22日   27   0   0 二叉树二叉树
hI6KHgNRyc1X