#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
*/
二叉树的相关操作+先序(中序,后序)遍历 + 非递归中序遍历
最新推荐文章于 2022-05-07 16:45:02 发布