算法导论——二叉查找树

代码部分实现,用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);

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值