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

一切都正常,只在最后一步运行出不能读

iambeliveble 发布于 2009-09-07 17:19, 416 次点击
#include<iostream.h>
 template<class T>
     struct BiNode
 {
     T data;
     BiNode<T> *lchild,*rchild;
 };
template<class T>
class erchashu
{
public:
    erchashu(int a[],int n);
    void insert(BiNode<T> *root,BiNode<T> *s);
private:
    BiNode<T> *root;
    BiNode<T> *s;
};
template<class T>
void erchashu<T>::insert(BiNode<T> *root,BiNode<T> *s)
{
    if(root==NULL)
        root=s;
    else if(s->data<root->data) insert(root->lchild,s);
          else insert(root->rchild,s);
}
template<class T>
erchashu<T>::erchashu(int a[],int n)
{
    for(int i=0;i<n;i++)
    {
        s=new BiNode<T>;s->data=a[i];
        s->lchild=s->rchild=NULL;
        insert(root,s);
    }
}
void main()
{
    int we[]={53,12,26,56,89,15,42,36};
    erchashu<int> b(we,8);
   
}
一切都正常,只在最后一步运行出不能读,什么原因
2 回复
#2
serious2009-09-08 05:35
原因是"root"的内容不是"NULL" :
程序代码:
template<class T>
erchashu<T>::erchashu(int a[],int n)
{
    root = NULL; //这里"root"的初始化
    for(int i=0;i<n;i++)
    {
        s=new BiNode<T>;s->data=a[i];
        s->lchild=s->rchild=NULL;
        insert(root,s);
    }
}
#3
wxjeacen2009-09-08 14:41
程序代码:
#include<iostream>                          
using namespace std;                        

template<class T>
struct BiNode
{            
    T data;   
    BiNode<T> *lchild,*rchild;
};                        
template<class T>
class BiTree
{
public:
    BiTree(int a[],int n);
    void insert(BiNode<T> *root,BiNode<T> *s);
private:
    BiNode<T> *root;
    BiNode<T> *s;
};
template<class T>
void BiTree<T>::insert(BiNode<T> *root,BiNode<T> *s)
{
    if(root==NULL)
        root=s;
    else if(s->data<root->data) insert(root->lchild,s);
    else insert(root->rchild,s);
}
template<class T>
BiTree<T>::BiTree(int a[],int n):root(NULL)
{
    for(int i=0;i<n;i++)
    {
        s=new BiNode<T>;
        s->data=a[i];
        s->lchild=s->rchild=NULL;
        insert(root,s);
    }
}
int main()
{
    int we[]={53,12,26,56,89,15,42,36};
    BiTree<int> b(we,8);
    return 0;
}
1