二叉排序树

来源:岁月联盟 编辑:猪蛋儿 时间:2012-11-17
[cpp] 
#include<iostream> 
using namespace std; 
 
struct BiTree 

    int data; 
    BiTree *Lchild; 
    BiTree *Rchild; 
}; 
 
void BiSort(BiTree *&root)  //数据的初始化 

    int Insert(BiTree *&root,BiTree *s); 
    int num; 
    cout<<"请输入节点数为:"; 
    cin>>num; 
    int *value=new int[num]; 
    int i; 
    cout<<endl<<"请输入各节点的值:"; 
    for(i=0;i<num;i++) 
        cin>>value[i]; 
    BiTree *t; 
    for(i=0;i<num;i++) 
    { 
        t=new BiTree; 
        t->data=value[i]; 
        t->Lchild=NULL; 
        t->Rchild=NULL; 
        Insert(root,t); 
    } 

 
int Insert(BiTree *&root,BiTree *s)  //插入数据 

    if(root==NULL)root=s; 
    else 
        if(s->data==root->data)return 0; 
        else 
            if(s->data>root->data)Insert(root->Rchild,s); 
            else 
                if(s->data<root->data)Insert(root->Lchild,s); 
    return 1; 

 
BiTree *Search(BiTree *&root,int n) 

    BiTree *temp=root; 
    if(root->data>n)temp=Search(root->Lchild,n); 
    else 
        if(root->data<n)temp=Search(root->Rchild,n); 
            return temp; 

 
int main() 

    BiTree *root; 
    BiTree root1; 
    root=NULL; 
    BiSort(root); 
    BiTree *temp; 
    cout<<"请输入你要查询的数字:"; 
    int n; 
    cin>>n; 
    temp=Search(root,n); 
    cout<<"你查询的数字是:"<<temp->data<<"并已经找到!"<<endl; 
    return 0; 

下一篇:返回列表