二叉排序树中序遍历不能出来,希望大家看看,分不是很多
#include<iostream>
using namespace std;
template <class T>
struct BiNode//二叉树结点的类型
{
T data;
BiNode* lchild;
BiNode* rchild;
};
template <class T>
class BiSortTree
{
private:
BiNode<T>* root;
int count;
public:
BiNode<T>* getroot();//取根节点的地址
~ BiSortTree() {}
BiSortTree(T r[ ], int n);
void InsertBST(BiNode<T> *root, BiNode<T> *s);
BiNode<T> * SearchBST(BiNode<T> *root, int k);
void InOrder(BiNode<T> *root);//中序遍历
};
template <class T>
BiNode<T>* BiSortTree<T>::getroot()
{
return root ;
}
template <class T>
BiSortTree<T>::BiSortTree(T r[ ], int n) //构造函数
{ BiNode<T> *s=NULL;
root=NULL;
for (int i = 0; i < n; i++)
{
s = new BiNode<T>;
s->data = r[i];
s->lchild=s->rchild=NULL;
InsertBST(root, s);
}
}
template <class T>
void BiSortTree<T>::InsertBST(BiNode<T> *root, BiNode<T> *s)//动态的加入结点
{
if (root==NULL)
root=s;
else if (s->data<root->data)
InsertBST(root->lchild, s);
else
InsertBST(root->rchild, s);
}
template <class T>
BiNode<T> * BiSortTree<T>::SearchBST(BiNode<T> *root, int k)
{
if (root == NULL)
return NULL;
else if(root->data == k)
return root;
else if (k < root->data)
return SearchBST(root->lchild, k);
else
return SearchBST(root->rchild, k);
}
template <class T>
void BiSortTree<T>::InOrder(BiNode<T> *root)
{
if (root!=NULL)
{
InOrder(root->lchild);
cout<<root->data<<" ";
InOrder(root->rchild);
}
}
void main()
{
int ia[8];
cout<<"请输入8个int型数据"<<endl;
for(int i=0;i<8;i++)
cin>>ia[i];
BiSortTree<int>a(ia,8);
cout<<"中序遍历:\n";
a.InOrder(a.getroot());
cout<<endl;
}
中序遍历不能够输出来,请求大家帮忙修改下
[解决办法]
问题在你的动态插入函数
InsertBST(BiNode<T> *root, BiNode<T> *s)
你操作的实际上是形参root,实际的root依然是NULL。
所以这里要用2重指针或引用,试下这个吧。
template <class T>
void BiSortTree<T>::InsertBST(BiNode<T> **root, BiNode<T> *s)//动态的加入结点
{
if (*root==NULL)
*root=s;
else if (s->data<(*root)->data)
InsertBST(&((*root)->lchild), s);
else
InsertBST(&((*root)->rchild), s);
}
[解决办法]
template <class T>
void BiSortTree<T>::InsertBST(BiNode<T> *&root, BiNode<T> *s)//动态的加入结点
{ //上面加了个引用
if (root==NULL)
root=s;
else if (s->data<root->data)
InsertBST(root->lchild, s);
else
InsertBST(root->rchild, s);
}
类似的问题的解释和解决请看我的一篇博客,讲的很详细,我就曾经遇到过类似的问题:
http://blog.csdn.net/zlhy_/article/details/8219652