二叉树的相关操作+先序(中序,后序)遍历 + 非递归中序遍历

#include<iostream>
#include<cstdio>
#include<stack>
using namespace std ;

typedef struct node  //树节点的结构体
{
	char data ;
	struct node *lchild , *rchild ;
}node , *tree ;


/* 创建一棵树 */
bool CreateTree(tree &T)
{
	char ch ;
	//cin >> ch ;
	scanf("%c",&ch);
	if(ch == ' ') {
		T = NULL;
		return true;
	}
	T = (node *)malloc(sizeof(node));
	if(!T)
		exit(1) ;
	T->data = ch ;
	CreateTree(T->lchild ) ;
	CreateTree(T->rchild ) ;
	return true ;
}

/*输出函数*/
void outprint(char a)
{
	cout<<a;
}

/*先序遍历*/
void PreTra(tree T)
{
	if(T)
	{
		outprint(T->data );
		PreTra(T->lchild);
		PreTra(T->rchild);
	}
}

/*中序遍历 */
void MidTra(tree T)
{
	if(T)
	{
		MidTra(T->lchild);
		outprint(T->data);
		MidTra(T->rchild);
	}
}

/*非递归中序遍历*/
void nMidTra(tree T)
{
	stack<tree>s ; 
	tree p;
	p = T ;
	while(p||!s.empty()) 
	{
		if(p){//遍历左孩子
			s.push(p);
			p = p ->lchild ;
		}
		else //遍历右孩子
		{
			p = s.top();
			outprint(p->data);
			s.pop();
			p = p->rchild ;
		}
	}
}

/*后序遍历*/
void LastTra(tree T)
{
	if(T)
	{
		LastTra(T->lchild ) ;
		LastTra(T->rchild ) ;
		outprint(T->data );
	}
}

int main(void)
{
	tree T;
	T = (node *)malloc(sizeof(node)) ;
	if(!T){
		cout<<"overflow"<<endl ;
		exit(1) ;
	}
	CreateTree(T) ;
	
	cout << "先序遍历:   " ;
	PreTra(T);
	cout << endl;
	
	cout << "中序遍历:   " ;
	MidTra(T);
	cout<<endl ;
	
	cout << "非递归中序遍历 :  " ;
	nMidTra(T);
	cout<<endl;

	cout << "后序遍历:   " ;
	LastTra(T) ;
	cout<<endl ;

	return 0;
}

/*
输入:
ABC  DE G  F   

*/

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值