c语言表达式树的创建,中序表达式如何构建二叉树(C语言)?

60fe2fdcaf6a0f0471234d90faa1de31.png

非常感谢你如此热心的帮助!下面是我同学用C++编的,其中删除树用的是你的代码,分享一下:

#include

struct Node

{

char data;

Node *leftchild,*rightchild;

};

class stack

{

Node * *data1;

int top;

int maxize;

public:

stack(int i);

void push(Node *a);

Node *pop();

};

stack::stack(int max)

{

maxize=max;

top=-1;

data1=new Node *[maxize];

}

void stack::push(Node *a)//入栈

{

data1[++top]=a;

}

Node *stack::pop()//出栈

{

if(top<0)

{

return 0;

top--;

}

else

{

return data1[top--];

}

}

Node *fun()//创建二叉树

{

char temp;

stack stack1(100);

cout<

Node *p;

while(cin.get(temp))

{

if(temp=='\n') break;

if(temp'z')

{

p=new Node();

p->data=temp;

p->rightchild=stack1.pop();

p->leftchild=stack1.pop();

stack1.push(p);

}

else

{

p=new Node();

p->data=temp;

p->rightchild=0;

p->leftchild=0;

stack1.push(p);

}

}

return stack1.pop();

}

void xianxu(Node *a)//先序遍历

{

if(a!=0)

{

cout<data;

xianxu(a->leftchild);

xianxu(a->rightchild);

}

}

void zhongxu(Node *a)//中序遍历

{

if(a!=0)

{

zhongxu(a->leftchild);

cout << a->data;

zhongxu(a->rightchild);

}

}

void houxu(Node *a)//后序遍历

{

if(a!=0)

{

houxu(a->leftchild);

houxu(a->rightchild);

cout <data;

}

}

int Depth (Node *T ) // 返回二叉树的深度

{

int depth1;

if( !T ) depth1 = 0;

else

{

int depthleft = Depth( T->leftchild );

int depthright= Depth( T->rightchild );

depth1 = 1 + (depthleft > depthright ?

depthleft : depthright);

}

return depth1;

}

void funtion(int c,char temp)

{

for(int i=0;i

{

cout<

}

cout<

}

void print(Node *a,int c)//打印二叉树

{

if(a==0) return;

if(a->rightchild)

{

print(a->rightchild,c+1);

}

funtion(c,a->data);

if(a->leftchild)

{

print(a->leftchild,c+1);

}

}

void Tree_Destroy(Node *t) //删除整个树

{

if (t!=0&&t->leftchild!=0)

Tree_Destroy(t->leftchild);

if(t!=0&&t->rightchild!=0)

Tree_Destroy(t->rightchild);

delete t;

}

//主函数

void main()

{

Node *q;

q=fun();

cout<

xianxu(q);

cout<

cout<

zhongxu(q);

cout<

cout<

houxu(q);

cout<

int d=Depth(q);

print(q,d);

Tree_Destroy(q);

}

◆◆

评论读取中....

请登录后再发表评论!

◆◆

修改失败,请稍后尝试

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值