二叉树的创建+递归遍历+非递归遍历

#include<iostream>
#include<stdlib.h>
#define MAXSIZE 100
typedef char ElementType; 
using namespace std;

typedef struct BTNode{
	ElementType data;
	struct BTNode *lChild;
	struct BTNode *rChild;
}BTNode;
void createBinaryTree(BTNode *&bt)
{
	ElementType data;
	bt = (BTNode *)malloc(sizeof(BTNode));
	cin>>data;
	if(data == '#')
	{
		bt = NULL;
	}
	else
	{
		bt->data = data;
		createBinaryTree(bt->lChild);
		createBinaryTree(bt->rChild);
	}
}
void preOrderRecursionVisit(BTNode *bt)
{
	if(bt == NULL)
		return;
	else
	{
		cout<<bt->data<<" ";
		preOrderRecursionVisit(bt->lChild);
		preOrderRecursionVisit(bt->rChild);
	}
}

void preOrderNonRecursionVisit(BTNode *bt)
{
	if(bt == NULL)
		return;
	BTNode *stack[MAXSIZE], *tNode;
	int top = -1;
	stack[++top] = bt;
	while(top != -1)
	{
		tNode = stack[top--];
		cout<<tNode->data<<" ";
		if(tNode->rChild != NULL)
			stack[++top] = tNode->rChild;
		if(tNode->lChild != NULL)
			stack[++top] = tNode->lChild;
	}
	cout<<endl; 
}

void inOrderRecursionVisit(BTNode *bt)
{
	if(bt == NULL)
		return;
	else
	{
		inOrderRecursionVisit(bt->lChild);
		cout<<bt->data<<" ";
		inOrderRecursionVisit(bt->rChild);
	}
}
void inOrderNonRecursionVisit(BTNode *bt)
{
	if(bt == NULL)
		return;
	BTNode *stack[MAXSIZE], *tNode;
	int top = -1;
	tNode = bt;
	while(top != -1 || tNode != NULL)
	{
		while(tNode != NULL)
		{
			stack[++top] = tNode; 
			tNode = tNode->lChild; 
		}
		if(top != -1)
		{
			tNode = stack[top--];
			cout<<tNode->data<<" ";
			if(tNode->rChild != NULL)
				tNode = tNode->rChild;
			else
				tNode = NULL;
		}
	}
	cout<<endl; 
} 


void postOrderRecursionVisit(BTNode *bt)
{
	if(bt == NULL)
		return;
	else
	{
		postOrderRecursionVisit(bt->lChild);
		postOrderRecursionVisit(bt->rChild);
		cout<<bt->data<<" ";
	}
}
void postOrderNonRecursionVisit(BTNode *bt)
{
	if(bt == NULL)
		return;
	
	BTNode *tNode, *stack1[MAXSIZE], *stack2[MAXSIZE];
	int top1 = -1, top2 = -1;
	stack1[++top1] = bt;
	while(top1 != -1)
	{
		tNode = stack1[top1--];
		stack2[++top2] = tNode;
		if(tNode->lChild != NULL)
			stack1[++top1] = tNode->lChild;
		if(tNode->rChild != NULL)
			stack1[++top1] = tNode->rChild;
	}
	while(top2 != -1)
	{
		tNode = stack2[top2--];
		cout<<tNode->data<<" ";
	}
	cout<<endl;
}
int main()
{
	BTNode *bt = NULL;
	//124##57##8##3#69###
	createBinaryTree(bt);
	preOrderRecursionVisit(bt);
	cout<<endl; 
	preOrderNonRecursionVisit(bt);
	
	inOrderRecursionVisit(bt);
	cout<<endl;
	inOrderNonRecursionVisit(bt);
	postOrderRecursionVisit(bt);
	cout<<endl;
	postOrderNonRecursionVisit(bt);
	
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值