问题遇到的现象和发生背景
没有输出
为什么struct BiNode *s=SearchBST(root,k)的地址显示为0x0
问题相关代码,请勿粘贴截图
#ifndef __Search_H
#define __Search_H
using namespace std;
const int MaxSize=10;
template<class T>
struct BiNode
{
T data;
struct BiNode *lchild;
struct BiNode *rchild;
};
template<class T>
class BiSortTree
{
private:
struct BiNode<T> *root;
void InsertBST(struct BiNode<T> *bt,struct BiNode<T> *s);
void DeleteBST(struct BiNode<T> *bt,struct BiNode<T> *s);
struct BiNode<T> *SearchBST(struct BiNode<T> *bt,T k);
void Release(struct BiNode<T> *bt);
public:
BiSortTree(T a[],int n);
~BiSortTree();
void InsertBST(struct BiNode<T> *s);
void SearchBST(T k);
};
template<class T>BiSortTree<T>::BiSortTree(T a[],int n)
{
root=new struct BiNode<T>;
root->data=a[0];
root->lchild=NULL;
root->rchild=NULL;
for(int i=1;i<n;i++)
{
struct BiNode<T> *s=new struct BiNode<T>;
s->data=a[i];
s->lchild=NULL;
s->rchild=NULL;
InsertBST(root,s);
}
}
template<class T>void BiSortTree<T>::Release(struct BiNode<T> *bt)
{
if(bt==NULL)return;
else
{
Release(bt->lchild);
Release(bt->rchild);
delete bt;
}
}
template<class T>BiSortTree<T>::~BiSortTree()
{
Release(root);
}
template<class T>void BiSortTree<T>::InsertBST(struct BiNode<T> *bt,struct BiNode<T> *s)
{
if(bt==NULL)
{
bt=s;
}
else
{
if(s->data<bt->data)
InsertBST(bt->lchild,s);
else
InsertBST(bt->rchild,s);
}
}
template<class T>void BiSortTree<T>::InsertBST(struct BiNode<T> *s)
{
InsertBST(root,s);
}
template<class T>struct BiNode<T> *BiSortTree<T>::SearchBST(struct BiNode<T> *bt,T k)
{
if(bt==NULL)
return NULL;
else
{
if(bt->data==k)
return bt;
else
{
if(k<bt->data)
{
return SearchBST(bt->lchild,k);
}
else
{
return SearchBST(bt->rchild,k);
}
}
}
}
template<class T>void BiSortTree<T>::SearchBST(T k)
{
struct BiNode<T> *s=SearchBST(root,k);
if(s->lchild==NULL)
cout<<"搜索的值的左子树为空";
else
cout<<s->lchild->data;
}
#endif // __Search_H
#include <iostream>
#include "Search.h"
using namespace std;
int main()
{
int a[MaxSize];
int n,k,data1,data2;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>k;
a[i]=k;
}
struct BiNode<int> *s=new struct BiNode<int>;
cin>>data1>>data2;
s->data=data1;
s->lchild=NULL;
s->rchild=NULL;
BiSortTree<int> Tree(a,n);
Tree.InsertBST(s);
Tree.SearchBST(data2);
return 0;
}