#include<iostream.h>
typedef char TreeData;
typedef struct BinTreeNode
{
TreeData data;
BinTreeNode *lchild,*rchild;
}BinTreeNode, *BinTree;
typedef BinTree StackData;
struct SeqStack
{ //顺序栈定义
StackData *base; //栈底指针
StackData *top; //栈顶指针
int StackSize;//当前已分配的全部存储空间
} ;
void InitStack ( SeqStack *S)
{ //置空栈
S->base =new StackData[100];
S->top = S->base;
S->StackSize=100;
}
int StackEmpty (SeqStack *S)
{
if( S->top == S->base ) return 1; //判栈空,空则返回1
else return 0; //否则返回0
}
void Push (SeqStack *S, StackData x)
{
//插入元素x为新的栈顶元素
*(S->top)=x;
(S->top)++;
}
int Pop (SeqStack *S, StackData &x) {
//若栈空返回0, 否则栈顶元素退出到x并返回1
if ( StackEmpty(S) ) return 0;
--(S->top);
x = *(S->top);
return 1;
}
BinTree CreateBinTree()
{
BinTree t=new BinTreeNode;
char ch;
cin>>ch;
if(ch!='*')
{
t->data=ch;
cout<<"请输入"<<ch<<"的左孩子:";
t->lchild=CreateBinTree();
cout<<"请输入"<<ch<<"的右孩子:";
t->rchild=CreateBinTree();
}
else t=NULL;
return t;
}
int BinTreeHeight(BinTree t)
{
if(t == NULL) return 0;
if(t->lchild== NULL && t->rchild == NULL) return 1;
int l_num=BinTreeHeight(t->lchild);
int r_num=BinTreeHeight(t->rchild);
if (l_num>r_num)return 1+l_num;
else return 1+r_num;
}
int BinTreeExchange(BinTree t)
{//相当于非第归中序遍历树,只是将visit变为交换
SeqStack s;
InitStack(&s);
BinTree p=t;
while(p||!StackEmpty(&s))
{
if(p)
{
Push(&s,p);p=p->lchild;
}
else
{
Pop(&s,p);
t=p->rchild;
p->rchild=p->lchild;
p->lchild=t;
p=p->lchild;//虽然还指向左子树但已经是原来的右子树了
}
}
return 1;
}// BinTreeExchange
void InOrder(BinTree t)
{
if(t)
{
InOrder(t->lchild);
cout<<t->data<<' ';
InOrder(t->rchild);
}
}
void main(void)
{
cout<<"建立一个二叉树,二叉树的数据为字符(若输入*表示该结点为空)\n";
cout<<"请输入该二叉树的根结点:\n";
BinTree t=CreateBinTree();
if(t==NULL)
{
cout<<"树为空,操作中止!\n";
return;
}
cout<<"\n\n\n";
cout<<"生成的二叉树的中序遍历为:";
InOrder(t);
cout<<endl;
cout<<"生成的二叉树的高度为:"<<BinTreeHeight(t)<<endl;
BinTreeExchange(t);
cout<<"进行左右子树交换后的二叉树的中序遍历为:";
InOrder(t);
cout<<endl;
}
评论1
最新资源