c语言利用遍历求树高的程序,[原创]用C语言写的求二叉树的建立,前中后遍历,深度以及结点个数的程序...

[原创]用C语言写的求二叉树的建立,前中后遍历,深度以及结点个数的程序

#include

#include

#define MaxSize 100

typedef char ElemType;

typedef struct node

{

ElemType data;

struct node *left,*right;

} BTree;

void creatree(BTree **BT,char *str)

{

BTree *stack[MaxSize],*p;

int top=-1,k,j=0;/*top为栈指针,k指定是左还是右孩子,j为str指针*/

char ch;

*BT=NULL;

ch=str[j];

while (ch!='\0')

{

switch(ch)

{

case '(':top++;stack[top]=p;k=1; /*为左结点*/

break;

case ')':top--;

break;

case ',':k=2; /*为右结点*/

break;

default: p=(BTree *)malloc(sizeof(BTree));

p->data=ch;p->left=p->right=NULL;

if (*BT==NULL) /*根结点*/

*BT=p;

else

{

switch(k)

{

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

break;

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

}

}

}

j++;

ch=str[j];

}

}

void preorder(BTree *BT)

{

if (BT!=NULL)

{

printf("%c",BT->data);

preorder(BT->left);

preorder(BT->right);

}

}

void inorder(BTree *BT)

{

if (BT!=NULL)

{

inorder(BT->left);

printf("%c",BT->data);

inorder(BT->right);

}

}

void postorder(BTree *B)

{

if (B!=NULL)

{

postorder(B->left);

postorder(B->right);

printf("%c",B->data);

}

}

int BTreeDepth(BTree *B)

{

int leftdep,rightdep;

if (B==NULL)

return(0);

else

{

leftdep=BTreeDepth(B->left);

rightdep=BTreeDepth(B->right);

if (leftdep>rightdep)

return(leftdep+1);

else

return(rightdep+1);

}

}

int leafcount(BTree *B)

{

if (B==NULL)

return(0);

else if (B->left==NULL && B->right==NULL)

return(1);

else

return(leafcount(B->left)+leafcount(B->right));

}

main()

{

BTree *B;

char *s="A(B(D,E(H,I)),C(G))";

creatree(&B,s);

printf("\n前序遍历:");

preorder(B);

printf("\n中序遍历:");

inorder(B);

printf("\n后序遍历:");

postorder(B);

printf("\nthe deepth is%d\n",BTreeDepth(B));

printf("the leafcount is %d\n",leafcount(B));

}

谢谢曾经给我的提示,以后希望大家一起努力!!!!!

13a2f4bd84d8af35e7645442bb7a26a3.gif

13a2f4bd84d8af35e7645442bb7a26a3.gif

13a2f4bd84d8af35e7645442bb7a26a3.gif

13a2f4bd84d8af35e7645442bb7a26a3.gif

13a2f4bd84d8af35e7645442bb7a26a3.gif

13a2f4bd84d8af35e7645442bb7a26a3.gif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值