非常感谢你如此热心的帮助!下面是我同学用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);
}
◆◆
评论读取中....
请登录后再发表评论!
◆◆
修改失败,请稍后尝试