C语言实现二叉树的遍历(非递归)

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

typedef struct TreeNode
{
	char data;
	struct TreeNode* lchild;
	struct TreeNode* rchild;
	int flag;//非递归后序遍历
}TreeNode;

typedef struct StackNode
{
	TreeNode* data;
	struct Stack* next;
}StackNode;

StackNode* StackInit(TreeNode* T)//利用栈对树进行遍历
{
	StackNode* S = (StackNode*)malloc(sizeof(StackNode));
	S->data = NULL;
	S->next = NULL;
	return S;
}

void createTree(TreeNode** T,char* data,int* index)
{
	char ch;
	ch = data[*index];
	*index += 1;
	if (ch == NULL)
	{
		*T = NULL;
	}
	else
	{
		*T = (TreeNode*)malloc(sizeof(TreeNode));
		(*T)->data = ch;
		(*T)->flag = 0;
		createTree((*T)->lchild, data, index);
		createTree((*T)->rchild, data, index);
	}
}

void Push(TreeNode* data, StackNode* S)//入栈
{
	StackNode* node = (StackNode*)malloc(sizeof(StackNode));
	node->data = data;
	node->next = S->next;
	S->next = node;
}

int isEmpty(StackNode* S)
{
	if (S->next == NULL)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

StackNode* popStack(StackNode* S)//出栈
{
	if (isEmpty(S))
	{
		return NULL;
	}
	else
	{
		StackNode* node = S->next;
		S->next = node->next;
		return node;
	}
}

StackNode* gettopStack(StackNode* S)//栈顶元素
{
	if (isEmpty(S))
	{
		return NULL;
	}
	else
	{
		StackNode* node = S->next;
		return node;
	}
}


void preOrder(TreeNode* T)//先序遍历(非递归)
{
	TreeNode* node = T;
	StackNode* S = StackInit(S);
	while (node || !isEmpty(S))
	{
		if (node)
		{
			printf("%c ",node->data);
			Push(node,S);
			node = node->lchild;
		}
		else
		{
			node = popStack(S)->data;
			node = node->rchild;
		}
	}
}

void inOrder(TreeNode* T)//中序遍历(非递归)
{
	TreeNode* node = T;
	StackNode* S = StackInit(S);
	while (node || !isEmpty(S))
	{
		if (node)
		{	
			Push(node, S);
			node = node->lchild;
		}
		else
		{
			node = popStack(S)->data;
			printf("%c ", node->data);
			node = node->rchild;
		}
	}
}

//后序遍历:从根节点开始寻找最左边的节点,
//依次入栈,出栈前,判断其是否有右子树,
//并且未被访问,则将其有子树入栈。
void postOrder(TreeNode* T)
{
	TreeNode* node = T;
	StackNode* S = StackInit(S);
	while (node || !isEmpty(S))
	{
		if (node)
		{
			Push(node, S);
			node = node->lchild;
		}
		else
		{
			TreeNode* top = gettopStack(S)->data;
			if (top->rchild && top->rchild->flag == 0)
			{
				top=top->rchild;
				Push(top, S);
				node = top->lchild;
			}
			else
			{
				top = popStack(S)->data;
				printf("%c ",top->data);
				top->flag = 1;
			}
		}
	}
}

int main(int argc,char* argv[])
{
	TreeNode* T;
	int index = 0;
	createTree(&T, argv[1], &index);
	preOrder(T);
	printf("\n");
	inOrder(T);
	printf("\n");
	postOrder(T);
	printf("\n");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值