排序binary tree

#include <iostream>
#include <cstdlib>

using namespace std;


class myNode
{
    private:
        int data;
        myNode *lchild;
        myNode *rchild;
    public:
        myNode();
        friend class myBTree;
};
myNode::myNode()
{
    data=0;
    lchild=NULL;
    rchild=NULL;
}

class myBTree
{
    private:
    public:
        myBTree(){};
        void insert(myNode *&,int );
        void preorder(myNode *p);
        void inorder(myNode *p);
        void postorder(myNode *p);
};
void myBTree::insert(myNode *& p,int x)
{
    if(p==NULL)
    {
        p=new myNode;
        p->data=x;
        p->lchild=NULL;
        p->rchild=NULL;
    }
    else
    {
        if(x<=p->data)
        {
            insert(p->lchild,x);
        }
        else
        {
            insert(p->rchild,x);
        }
    }
}
void myBTree::inorder(myNode *p)
{
    if(p!=NULL)
    {
        inorder(p->lchild);
        cout<<p->data<<"-->";
        inorder(p->rchild);
    }
}
void myBTree::preorder(myNode *p)
{
    if(p!=NULL)
    {
        cout<<p->data<<"-->";
        preorder(p->lchild);
        preorder(p->rchild);
    }
}
void myBTree::postorder(myNode *p)
{
    if(p!=NULL)
    {
        postorder(p->lchild);
        postorder(p->rchild);
        cout<<p->data<<"-->";
    }
}
int main()
{
    cout << "Hello world!" << endl;
    myNode *head=NULL;
    myBTree *p=new myBTree;
    p->insert(head,6);
    p->insert(head,4);
    p->insert(head,8);
    p->insert(head,3);
    p->insert(head,5);
    p->insert(head,7);
    p->insert(head,9);

    p->inorder(head);
    cout<<endl;
    p->preorder(head);
    cout<<endl;
    p->postorder(head);
    cout<<endl;

    delete p;
    delete head;
    cout<<endl;
    int a=8,b=16;
    a>b?(cout<<"a great than b."):(cout<<"b is great than a.");
    return 0;
}

ios

相關文章
相關標籤/搜索