WEB开发网
开发学院软件开发C++ 二叉树的先序遍历(非递归) 阅读

二叉树的先序遍历(非递归)

 2012-05-25 07:53:23 来源:WEB开发网   
核心提示:#include<stdio.h>#include<stdlib.h>typedef struct Bitree{int data;struct Bitree *Lchild,*Rchild;}BitreeNode,*LinkBitree;typedef struct Stack{LinkBit
#include<stdio.h>
#include<stdlib.h>

typedef struct Bitree
{
	int data;
	struct Bitree *Lchild,*Rchild;
}BitreeNode,*LinkBitree;

typedef struct Stack
{
	LinkBitree data[20];
	int top,bottom;
}Stack,*StackList;

LinkBitree CreatBitree();

StackList InitStack();

void InorderTraverse(LinkBitree,StackList);

int main()
{
	LinkBitree BitreeHead;
	StackList Stack;
	printf("请输入根结点的值:e=  ");
	BitreeHead=CreatBitree();
	Stack=InitStack();
	InorderTraverse(BitreeHead,Stack);
	return 0;
}

LinkBitree CreatBitree()
{
	int edata;
	LinkBitree Head;
	scanf("%d",&edata);
	if(edata==0)
	{
		Head=NULL;
	}
	else
	{
		Head=(LinkBitree)malloc(sizeof(BitreeNode));
	    if(Head==NULL)
		{
			printf("内存分配失败!!");
		    exit(0);
		}
		else
		{
			Head->data=edata;
			printf("请输入结点%d的左孩子的值:e= ",Head->data);
			Head->Lchild=CreatBitree();
			printf("请输入结点%d的右孩子的值:e= ",Head->data);
			Head->Rchild=CreatBitree();
		}
	}
	return Head;
}


StackList InitStack()
{
	StackList Stack;
	Stack=(StackList)malloc(sizeof(Stack));
	if(Stack==NULL)
	{
		printf("内存分配失败!!");
		exit(0);
	}
	else
	{
		Stack->top=0;
		Stack->bottom=0;
	}
	return Stack;
}


void InorderTraverse(LinkBitree Head,StackList Stack)
{
	do
	{
		while(Head)
		{
			printf("%d ",Head->data);
			Stack->data[Stack->top]=Head;
			Stack->top=Stack->top+1;
			Head=Head->Lchild;
		}
		if(Stack->top)
		{
			Stack->top--;
			Head=Stack->data[Stack->top];
			Head=Head->Rchild;
		}
	}while(Stack->top||Head);
}

Tags:遍历 递归

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接