二叉树遍历操作[1]

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

/************二叉树操作***************/

#include

using namespace std;

struct BiTree

{

char data ;

BiTree *left ;

BiTree *right ;

};

BiTree *CreateBiTree()//建立二叉树

{

BiTree *S[100],*b,*p;

int i=0,k,l=0,top=0;

char str[100] ;

char ch;

b=NULL;

while((ch=cin.get())!='#')

str[l++]=ch;

str[l]='\0';

while(str[i])

{

switch(str[i])

{

case '(' :S[++top]=p; k=1; break ;

case ')' :top--; break ;

case ',' : k=2; break ;

default :

{

p=new BiTree ;

p->data=str[i];

p->left=NULL;

p->right=NULL ;

if(b==NULL)

b=p;

else

{

switch(k)

{

case 1:S[top]->left=p; break;

case 2:S[top]->right=p; break;

}

}

}

}

}cout<<"已为您成功录入二叉树!"<

return b ;

}

void Inorder(BiTree *root)//中序遍历函数{

if (root!=NULL)

{

Inorder(root->left );

cout<data;

Inorder(root->right );

}

}

void preorder(BiTree *root)//先序遍历

{ if (root!=NULL)

{

cout<data;

preorder(root->left);

preorder(root->right);

}

}

void lateorder(BiTree *root)//后序遍历

{

if (root!=NULL)

{

lateorder(root->left);

lateorder(root->right);

cout<data;

}

}

void leftorder(BiTree *p)//层次遍历

{

BiTree *qu[100];

int front=0,rear=0;

if(p!=NULL)

cout<data;

rear++;

qu[rear]=p;

while(rear!=front)

{

front=(front+1)%100;

p=qu[front];

if(p->left!=NULL)

cout<left->data;

rear=(rear+1)%100;

qu[rear]=p->left;

}

if(p->right!=NULL)

{

cout<right->data;

rear=(rear+1)%100;

qu[rear]=p->right;

}

}

}

int max(int a,int b)

{

return a>b?a:b;

}

int NodeCount ( BiTree *b )//求结点个数

{ int L,R;

if ( b==NULL ) return 0;

L = NodeCount ( b->left );

R = NodeCount ( b->right );

return 1+L+R;

}

int LeafCount ( BiTree *b )//求叶子结点个数{ int L,R;

if ( b==NULL ) return 0;

if ( b->left==NULL && b->right==NULL)

return 1;

L = LeafCount ( b->left );

R = LeafCount ( b->right );

return L + R;

}

int max1(int a,int b)

{

return a>b?a:b;

}

int Depth ( BiTree *b )//求深度

{int L,R;

if ( b==NULL ) return 0;

L=Depth ( b->left );

R=Depth ( b->right );

return 1+max1(L,R);

}

相关文档
最新文档