二叉树基本操作(1)

时间:2021-10-20 17:30:39
#include<cstdlib>
#include<iostream>
#include<cstdio>
#define MaxSize 20
using namespace std;
typedef char ElemType;

typedef struct node{
ElemType data;
struct node *lchild;
struct node *rchild;
}BTNode;
//创建二叉树CreateBTNode(*b,*str)
void CreateBTNode(BTNode *&b,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->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];
}
}
//查找节点FindNode(*b,x)
BTNode *FindNode(BTNode *b,ElemType x)
{
BTNode *p;
if(b==NULL)
return NULL;
else if(b->data==x)
return b;
else
{
p=FindNode(b->lchild,x);
if(p!=NULL)
return p;
else
return FindNode(b->rchild,x);
}
}
//找孩子节点LchildNode(p)和RchildNode(p)
BTNode *LchildNode(BTNode *p)
{
return p->lchild;
}
BTNode *RchildNode(BTNode *p)
{
return p->rchild;
}
//求高度:递归算法
int BTNodeHeight(BTNode *b)
{
int lchildh,rchildh;
if(b==NULL)
return (0);
else
{
lchildh=BTNodeHeight(b->lchild);
rchildh=BTNodeHeight(b->rchild);
return (lchildh>rchildh)?(lchildh+1):(rchildh+1);
}
}
//输出二叉树
void DispBTNode(BTNode *b)
{
if(b!=NULL)
{
cout<<b->data;
if(b->lchild!=NULL||b->rchild!=NULL)
{
cout<<"(";
DispBTNode(b->lchild);
if(b->rchild!=NULL)
cout<<",";
DispBTNode(b->rchild);
cout<<")";
}
}
}
int main()
{
BTNode *b;
CreateBTNode(*&b,"A(B(D(,G)),C(E,F))");
DispBTNode(b);
}