注册 登录
编程论坛 C++教室

请各位变成高手给查查错

spoorty 发布于 2012-12-06 15:19, 255 次点击
#include <iostream>
using namespace std;
struct t
{
    char e;
    t *lc,*rc;
};
int whil=1;
void ct(t *root)
{
    char ee;
    cin>>ee;
    if(ee=='.') root=NULL;
    else
    {
        root=new t;
        root->e=ee;
        ct(root->lc);
        ct(root->rc);
    }
}
void dlr(t *root)
{
    if(root!=NULL)
    {
        cout<<root->e;
        dlr(root->lc);
        dlr(root->rc);
    }
    cout<<endl<<"先序遍历完成"<<endl;
}
void ldr(t *root)
{
    if(root!=NULL)
    {
        ldr(root->lc);
        cout<<root->e;
        ldr(root->rc);
    }
    cout<<endl<<"中序遍历完成"<<endl;
}
void lrd(t *root)
{
    if(root!=NULL)
    {
        lrd(root->lc);
        lrd(root->rc);
        cout<<root->e;
    }
    cout<<endl<<"后序遍历完成"<<endl;
}
void vt(t *root)
{
    if(root!=NULL)
    {
        if(root->rc==NULL&&root->rc==NULL) cout<<root->e;
        dlr(root->lc);
        dlr(root->rc);
    }
    cout<<endl<<"叶子节点输出完成"<<endl;
}                                                
int main()
{
    t tree;
    while(whil)
    {
        char a;
        cout<<"请选择操作:1 创建树 2 遍历树 3 叶子结点输出 4 结束程序"<<endl;
        cin>>a;
        switch(a)
        {
        case '1':ct(&tree);break;
        case '2':
            {
                dlr(&tree);
                ldr(&tree);
                lrd(&tree);
            };break;
        case '3':ct(&tree);break;
        case '4':whil=0;break;
        default:cout<<"无此选项"<<endl;
        }
        system("pause");
        system("cls");
    }
    return 0;
}
这段关于二叉树的代码,为什么无法遍历
3 回复
#2
yuccn2012-12-06 15:46
1 递归时候没有必要每个节点都输出一下“后序遍历完成”之类的文章,提到最外面就行了
2 ct创建数的时候,带不出去的,并且你创建树的调用却是ct(&tree),传进去的是一个局部结构体地址,把它改成
 t *pTree = NULL;
 ct(&pTree)吧
同时ct()改成传进来的是t **类型。
或者你通过返回值带出去。
3 有创建树没有销毁树?
4 case 3的时候 ,你是想vt()遍历的吧,不是想调用ct()吧





[ 本帖最后由 yuccn 于 2012-12-6 15:51 编辑 ]
#3
yuccn2012-12-06 15:50
void ct(t **root)
 {
     char ee;
     cin>>ee;
     if(ee=='.') *root=NULL;
     else
     {
         *root=new t;
         (*root)->e=ee;
         ct(&(*root)->lc);
         ct(&(*root)->rc);
     }
 }
int main()
 {
     t *tree = NULL;
     while(whil)
     {
         char a;
         cout<<"请选择操作:1 创建树 2 遍历树 3 叶子结点输出 4 结束程序"<<endl;
         cin>>a;
         switch(a)
         {
         case '1':ct(&tree);break;
         case '2':
             {
                 dlr(&tree);
                 ldr(&tree);
                 lrd(&tree);
             };break;
          // …………
         }
     }
     return 0;
 }
#4
spoorty2012-12-09 14:41
自己没电脑,所以上线检查的晚了,谢谢版主回答!
1