C++ 建立并搜寻二叉查找树
C++ 建立并搜索二叉查找树
#include<iostream>
using namespace std;
struct BiNode
{
int data;
BiNode * lchild;
BiNode * rchild;
};
void InsertBST(BiNode * root,int data)//插入结点
{
if(root==NULL)
{
root=new BiNode;
root->data=data;
root->lchild =root->rchild =NULL;
}
if(root->data >data)
InsertBST(root->lchild ,data);
if(root->data <data)
InsertBST(root->rchild ,data);
}
BiNode * CreateBST(BiNode * root,int data[],int n)//创建二叉树
{
int i;
for(i=0;i<n;i++)
InsertBST(root,data[i]);
return root;
}
void PrintBST(BiNode * root)//先序搜索二叉树
{
if(root!=NULL)
{
cout<<root->data ;
PrintBST(root->lchild );
PrintBST(root->rchild );
}
}
int main()
{
BiNode * root=NULL;
int data[10]={5,9,4,7,3,6,1,8,2,10};
root=CreateBST(root,data,10);
PrintBST(root);
cout<<endl;
return 0;
}
为什么会出错啊!难道是根结点要使用指针的指针吗?
------解决思路----------------------
楼主,一步步调试自然会发现问题。
#include<iostream>
using namespace std;
struct BiNode
{
int data;
BiNode * lchild;
BiNode * rchild;
};
void InsertBST(BiNode * root,int data)//插入结点
{
if(root==NULL)
{
root=new BiNode;
root->data=data;
root->lchild =root->rchild =NULL;
}
if(root->data >data)
InsertBST(root->lchild ,data);
if(root->data <data)
InsertBST(root->rchild ,data);
}
BiNode * CreateBST(BiNode * root,int data[],int n)//创建二叉树
{
int i;
for(i=0;i<n;i++)
InsertBST(root,data[i]);
return root;
}
void PrintBST(BiNode * root)//先序搜索二叉树
{
if(root!=NULL)
{
cout<<root->data ;
PrintBST(root->lchild );
PrintBST(root->rchild );
}
}
int main()
{
BiNode * root=NULL;
int data[10]={5,9,4,7,3,6,1,8,2,10};
root=CreateBST(root,data,10);
PrintBST(root);
cout<<endl;
return 0;
}
为什么会出错啊!难道是根结点要使用指针的指针吗?
------解决思路----------------------
楼主,一步步调试自然会发现问题。
struct BiNode
{
int data;
BiNode * lchild;
BiNode * rchild;
};
BiNode * InsertBST(BiNode * root,int data)//插入结点
{
if(root==NULL)
{
root=new BiNode;
root->data=data;
root->lchild =root->rchild =NULL;
}
if(root->data >data)
root->lchild = InsertBST(root->lchild ,data);
if(root->data <data)
root->rchild = InsertBST(root->rchild ,data);
return root;
}
BiNode * CreateBST(BiNode * root,int data[],int n)//创建二叉树
{
int i;
for(i=0;i<n;i++)
root = InsertBST(root,data[i]);
return root;
}
void PrintBST(BiNode * root)//先序搜索二叉树
{
if(root!=NULL)
{
cout<<root->data<<"->" ;
PrintBST(root->lchild );
PrintBST(root->rchild );
}
}
int main(int argc, char* *argv)
{
BiNode * root=NULL;
int data[10]={5,9,4,7,3,6,1,8,2,10};
root=CreateBST(root,data,10);
PrintBST(root);
cout<<endl;
return 0;
}