C语言顺序数组输出二叉树图,按先序次序建立以下二叉树,然后按先序的顺序输出结点的值、层次、左右孩子结点;用C语言编写,初学数据结...

这篇博客介绍了如何创建二叉树,并提供了先序遍历的实现。同时,它还包含了计算二叉树叶子节点数量和树的深度的函数。在修改后的代码中,增加了输出每个节点层次的功能,使得在先序遍历过程中可以显示节点所在的层次。
摘要由CSDN通过智能技术生成

#include

#include

#include

#define TRUE 1

#define FALSE 0

#define OK 1

#define ERROR 0

#define INFEASIBLE -1

#define OVERFLOW -2

typedef int Status;

typedef char elemtype;

typedef struct BiTNode{

elemtype data;

struct BiTNode *lchild,*rchild;

}BiTNode,*BiTree;

//构造二叉树

Status CreateBiTree(BiTree &T){

elemtype ch;

ch=getchar();

if(ch==' '){T=NULL;}

else{

if(!(T=(BiTNode *)malloc(sizeof(BiTNode))))

return FALSE;

T->data=ch;

CreateBiTree(T->lchild);

CreateBiTree(T->rchild);

}

return OK;

}

// 先序遍历

void PreOrderTraverse(BiTree T){

if(T!=NULL){

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

PreOrderTraverse(T->lchild);

PreOrderTraverse(T->rchild);

}

}

//叶子节点的个数

Status Leafnumber(BiTree T){

int num1=0,num2=0;

if(T==NULL)

return 0;

else if (T->lchild==NULL&&T->rchild==NULL) return 1;

else

{

num1=Leafnumber(T->lchild);

num2=Leafnumber(T->rchild);

return(num1+num2);

}

}

//树的深度

Status DepthTree(BiTree T){

int llength=0,rlength=0;

if(T==NULL) return 0;

else{

llength=DepthTree(T->lchild);

rlength=DepthTree(T->rchild);

return(llength>rlength)?(llength+1):(rlength+1);

}

}

void main()

{

BiTree s;

printf("输入字符串,使用空格代表空\n");

CreateBiTree(s);

printf("先序输出:\n");

PreOrderTraverse(s);

printf("\n树的深度:%d\n",DepthTree(s));

getch();

}

再问: 怎么输出每个结点的层次

再答: //增加个变量i,修改一下PreOrderTraverse #include #include #include #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 typedef int Status; typedef char elemtype; typedef struct BiTNode{ elemtype data; struct BiTNode *lchild,*rchild; }BiTNode,*BiTree; //构造二叉树 Status CreateBiTree(BiTree &T){ elemtype ch; ch=getchar(); if(ch==' '){T=NULL;} else{ if(!(T=(BiTNode *)malloc(sizeof(BiTNode)))) return FALSE; T->data=ch; CreateBiTree(T->lchild); CreateBiTree(T->rchild); } return OK; } // 先序遍历 void PreOrderTraverse(BiTree T,int i) { if(T!=NULL) { printf("%c\t%d\n",T->data,i); PreOrderTraverse(T->lchild,i+1); PreOrderTraverse(T->rchild,i+1); } } //叶子节点的个数 Status Leafnumber(BiTree T){ int num1=0,num2=0; if(T==NULL) return 0; else if (T->lchild==NULL&&T->rchild==NULL) return 1; else { num1=Leafnumber(T->lchild); num2=Leafnumber(T->rchild); return(num1+num2); } } //树的深度 Status DepthTree(BiTree T) { int llength=0,rlength=0; if(T==NULL) return 0; else { llength=DepthTree(T->lchild); rlength=DepthTree(T->rchild); return(llength>rlength)?(llength+1):(rlength+1); } } void main() { BiTree s; int i=1; printf("输入字符串,使用空格代表空\n"); CreateBiTree(s); printf("先序输出:\n值\t层次\n"); PreOrderTraverse(s,i); printf("\n树的深度:%d\n",DepthTree(s)); getch(); }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值