c语言创建一棵树函数 c语言创建一颗二叉树

数据结构 如何创建一棵树 , 请给出c语言详细代码,谢谢刚刚回答了一个类似的问题 , 以下代码供参考:
#include "stdio.h"
#include "stdlib.h"
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef char TElemType;
typedef int Status;
typedef struct BiTNode { // 结点结构
TElemTypedata;
struct BiTNode*lchild, *rchild;
// 左右孩子指针
} BiTNode, *BiTree;
//以下是建立二叉树存储结构,空节点输入作为#结束标识
Status CreateBiTree(BiTree T) {
//请将该算法补充完整,参见第6章课件算法或课本
char ch;
scanf("%c",ch);
if(ch=='#') T=NULL;
else{
if(!(T=(BiTNode*)malloc(sizeof(BiTNode))))
exit(OVERFLOW);
T-data=https://www.04ip.com/post/ch;
CreateBiTree(T-lchild);
CreateBiTree(T-rchild);
}
return OK;
} // CreateBiTree
void Preorder(BiTree T)
{
if(T)
{
printf("%c",T-data);
Preorder(T-lchild);
Preorder(T-rchild);
}
}
void Inorder(BiTree T)
{ // 中序遍历二叉树
//请将该算法补充完整,参见第6章课件算法
if(T)
{
Inorder(T-lchild);
printf("%c",T-data);
Inorder(T-rchild);
}
}
void Postorder(BiTree T)
{ // 后序遍历二叉树
//请将该算法补充完整,参见第6章课件算法
if(T)
{
Postorder(T-lchild);
Postorder(T-rchild);
printf("%c",T-data);
}
}
//以下是求叶子结点数
void CountLeaf(BiTree T,int count){
//请将该算法补充完整 , 参见第6章课件算法
if(T){
if((!T-lchild)(!T-rchild))
count++;
CountLeaf(T-lchild,count);
CountLeaf(T-rchild,count);
}
}
//以下是求二叉树的深度
int Depth(BiTree T ){
//请将该算法补充完整 , 参见第6章课件算法
int depthval,depthLeft,depthRight;
if(!T)depthval=0;
else{
depthLeft = Depth(T-lchild);
depthRight = Depth(T-rchild);
if(depthLeftdepthRight)depthval = 1+depthLeft;
else depthval = 1+depthRight;
}
return depthval;
}
void main(){
BiTree T;
int s=0,d;
printf("\n creat of the bitree:\n");
CreateBiTree(T);
printf("\n output result of Preorder:\n");
Preorder(T);
CountLeaf(T,s);
d=Depth(T);
printf("\n leaves=%d\n",s);
printf("\n depth=%d\n",d);
}
用C语言建立一棵二叉表达树并求值#includestdio.h
#includestring.h
#includemalloc.h
#includestdlib.h
#includemath.h
#defineSTACK_SIZE20
structOPND
{
intnum;
};
structOPTR
{
charop;
};
structOPND*ntop,*nbase;
structOPTR*otop,*obase;
intInitStackNum()
{
nbase=(OPND*)malloc(STACK_SIZE*sizeof(OPND));
if(!nbase)
exit(-1);
ntop=nbase;
return(1);
}
intInitStackOP()
{
obase=(OPTR*)malloc(STACK_SIZE*sizeof(OPTR));
if(!obase)
exit(-1);
otop=obase;
return(1);
}
intPushOPND(intInNum)
{
ntop-num=InNum;
ntop++;
return(1);
}
intPushOPTR(charInOP)
{
otop-op=InOP;
otop++;
return(1);
}
intPopOPND()
{
ntop--;
return(ntop-num);
}
charPopOPTR()
{
otop--;
return(otop-op);
}
intGetTopNum()
{
intGetNum;
ntop--;
GetNum=ntop-num;
ntop++;
return(GetNum);
}
charGetTopOP()
{
charGetOP;
otop--;
GetOP=otop-op;
otop++;
return(GetOP);
}
charCompareOP(charComChar)//此函数用于算符的优先级比较

推荐阅读