数据结构-----中序遍历二叉树非递归算法(利用堆栈实现)

一、非递归中序遍历算法思想

     (1)首先节点指针(一个”根”的指针)进栈,然后将节点指针指向进栈节点的左子树的根,重复(1),直到指针指向空(最后一个进栈的是最左子树),转(2);

         (2)堆栈非空时,从堆栈中退出一个节点的指针,访问该节点,转(3),堆栈为空时,结束算法;

         (3)然后将指针指向的访问过的节点的右子树的跟,转(1)。

二、代码实现

#include<stdio.h>
#include<stdlib.h>

typedef char EType; 

struct BinaryTreeNode
{
	EType data;
	struct BinaryTreeNode *LChild;
	struct BinaryTreeNode *RChild;
};
typedef BinaryTreeNode BinaryTree;

typedef struct SType
{
	BinaryTreeNode *ptr;
}SType;

typedef struct Stack
{
	SType *element;
	int top;
	int MaxSize;
}Stack;

void CreatStack(Stack &S,int MaxStackSize);
bool IsEmpty(Stack &S);
bool IsFull(Stack &S);
bool GetTop(Stack &S,SType &result);
bool Pop(Stack &S,SType &result);
bool Push(Stack &S,SType &x);
void CreatBiTree(BinaryTreeNode **BT);
void InOrderNoRecursive(BinaryTreeNode *BT);//跟前序遍历就是这点不同

int main()
{
    BinaryTreeNode *BT = NULL;
	CreatBiTree(&BT);//按照前序遍历输入方式构造一棵二叉树
	printf("中序遍历二叉树非递归算法输出为:");
	InOrderNoRecursive(BT);
	printf("\n");
	return 0;
}

void CreatStack(Stack &S,int MaxStackSize)
{
	S.MaxSize = MaxStackSize;
	S.element = new SType[S.MaxSize];
	S.top = -1;
}

bool IsEmpty(Stack &S)
{
	if(S.top == -1)
		return true;
	return false;
}

bool IsFull(Stack &S)
{
	if(S.top >= S.MaxSize-1)
		return true;
	return false;
}

bool GetTop(Stack &S,SType &result)
{
	if(IsEmpty(S))
		return false;
	result = S.element[S.top];
	return true;
}

bool Pop(Stack &S,SType &result)
{
	if(IsEmpty(S))
		return false;
	result = S.element[S.top];
	S.top--;
	return true;
}

bool Push(Stack &S,SType &x)
{
    if(IsFull(S))
		return false;
	S.top++;
	S.element[S.top] = x;
	return true;
}

void CreatBiTree(BinaryTreeNode **BT)
{
	EType tem;
	
	scanf("%c",&tem);
	if(' ' == tem)
	{
	    *BT = NULL;
	}
	else
	{
		*BT = new BinaryTreeNode;
		(*BT)->data = tem;
		CreatBiTree(&(*BT)->LChild);
        CreatBiTree(&(*BT)->RChild);
	}
}

void InOrderNoRecursive(BinaryTreeNode *BT)
{
	Stack S;
	SType temp;
	BinaryTreeNode *p = BT;
	int MaxStackSize = 50;
	CreatStack(S,MaxStackSize);

	while(p || !IsEmpty(S))
	{
		if(p)
		{
			temp.ptr = p;
			Push(S,temp);
			p = p->LChild;
		}
		else
		{
			if(!IsEmpty(S))
			{
				Pop(S,temp);
				p = temp.ptr;
				printf("%c\t",p->data);//跟前序遍历不同就是访问节点的时机不同
				p = p->RChild;
			}
		}
	}
}

三、
效果展示

建立这样一颗二叉树

《数据结构-----中序遍历二叉树非递归算法(利用堆栈实现)》

所以按照前序遍历输入应该是:“AB_D_ _CE_ _ _”(其中“_”代表空格)

那么运行结果为:

《数据结构-----中序遍历二叉树非递归算法(利用堆栈实现)》

    原文作者:递归算法
    原文地址: https://blog.csdn.net/zhouzixin053/article/details/24123549
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞