|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <iostream>
#include <malloc.h>
using namespace std;
#define MaxSize 50
typedef struct node
{
char data;
struct node *lchild;
struct node *rchild;
}BTNode;
//创建二叉树
void CreateBTree(BTNode *&b,const char *str)
{
BTNode *St[MaxSize],*p;
int top=-1,k,j=0;
char ch;
b=NULL;
ch=str[j];
while(ch!='\0')
{
switch(ch)
{
case '(':top++;St[top]=p;k=1;break;
case ')':top--;break;
case ',':k=2;break;
default:p=(BTNode *)malloc(sizeof(BTNode));
p->data=ch;
p->lchild=p->rchild=NULL;
if(b==NULL)
b=p;
else
{
switch(k)
{
case 1:St[top]->lchild=p;break;
case 2:St[top]->rchild=p;break;
}
}
}
j++;
ch=str[j];
}
}
//输出二叉树
void DispBTree(BTNode *b)
{
if(b!=NULL)
{
printf("%c",b->data);
if(b->lchild!=NULL||b->rchild!=NULL)
{
printf("(");
DispBTree(b->lchild);
if(b->rchild!=NULL)
printf(",");
DispBTree(b->rchild);
printf(")");
}
}
}
//销毁二叉树
void DestroyBTree(BTNode *&b)
{
if(b!=NULL)
{
DestroyBTree(b->lchild);
DestroyBTree(b->rchild);
free(b);
}
}
//找最小值的结点值
void FindMinNode(BTNode *b,char &min)
{
if(b->data<min)
min=b->data;
FindMinNode(b->lchild,min);//在左子树中找最小结点值
FindMinNode(b->rchild,min);//在右子树中找最小结点值
}
//输出最小结点值
void MinNode(BTNode *b)
{
if(b!=NULL)
{
char min=b->data;
FindMinNode(b,min);
printf("Min=%c\n",min);
}
}
int main()
{
BTNode *b;
CreateBTree(b,"E(B(D(,G)),C(A,F))");
cout<<"二叉树为:"<<endl;
DispBTree(b);
cout<<endl;
cout<<"最小结点值为:";
MinNode(b);
DestroyBTree(b);
return 0;
}
|
|