算法导论——二叉查找树

来源:互联网 发布:重庆seo俱乐部 编辑:程序博客网 时间:2024/06/04 22:46
代码部分实现,用insert生成二叉查找树。
暂无delete函数。
创建查找树是用insert逐个插入。
代码比较简陋,希望有所帮助。
#include<iostream>using namespace std;struct Node{    Node *left;    Node *right;    Node *parent;    int data;    Node(int x):left(NULL),right(NULL),parent(NULL),data(x){}};class searchtree{public:    Node*   root;    searchtree()    {       root=NULL;   };    void create()    {        int i;        while(cin>>i)        {            Node*   newnode=    new Node(i);            insert(newnode);        }    }    void insert(Node*   newnode)    {        if(root==NULL)  root=newnode;        else        {            Node*   y=NULL;            Node*   x=root;            while(x!=NULL)            {                y=x;                if(newnode->data>x->data)   x=x->right;                else    x=x->left;            }            newnode->parent=y;            if(newnode->data<y->data)   y->left=newnode;            else                                           y->right=newnode;        }    }    void order(Node* p)         //中序遍历    {        if(p!=NULL)      {           // cout<<p->data<<"  ";            order(p->left);           cout<<p->data<<"  ";            order(p->right);            //cout<<p->data<<"  ";      }    }    void preorder(Node* p)         //前序遍历    {        if(p!=NULL)      {            cout<<p->data<<"  ";            preorder(p->left);            preorder(p->right);      }    }    void nextorder(Node* p)         //后序遍历    {        if(p!=NULL)      {            nextorder(p->left);            nextorder(p->right);            cout<<p->data<<"  ";      }    }    Node* reroot()      {       return root;}    Node* Min(    Node *p)    {        while(p!=NULL)  p=p->left;        return p;    }    Node* Max (    Node *p)    {        while(p!=NULL)  p=p->right;        return p;    }    Node*   successor(Node * p)    {        if(p->right!=NULL)  return Min(p->right);        Node* y=p->parent;        while(y!=NULL&& p==y->right)        {            p=y;            y=y->parent;        }        return y;    }};int main(){    searchtree tree;    tree.create();    Node*   p=tree.reroot();    cout<<"中序遍历:";    tree.order(p);    cout<<endl;    cout<<"先序遍历:";    tree.preorder(p);    cout<<endl;    cout<<"后序遍历:";    tree.nextorder(p);}

原创粉丝点击