二叉搜索树

#include<iostream>
using namespace std;
typedef struct Node
{
    Node* left;
    Node* right;
    Node* p;
    int data;
    Node(){}
    Node(int dat) :data(dat){ left = right = NULL; }

}BT;
struct T
{
    BT *root;
    T(){ root = NULL; }
};
void Tree_Insert(T &tr, Node *z)
{
    Node* y = NULL;
    Node* x = tr.root;
    while (x != NULL)
    {
        y = x;
        if (z->data < x->data)
        {
            x = x->left;
        }
        else
            x = x->right;
    }
    z->p = y;
    if (y == NULL)
        tr.root = z;
    else if (z->data < y->data)
        y->left = z;
    else
        y->right = z;
}
void Inorder_Tree_Walk(Node*x)
{
    if (x != NULL)
    {
        Inorder_Tree_Walk(x->left);
        cout << x->data << "  ";
        Inorder_Tree_Walk(x->right);
    }

}
Node* Tree_Search(Node*x, int k)
{
    if((NULL==x)|| (k == x->data))
        return x;
    if (k < x->data)
    {
        return Tree_Search(x->left, k);
    }
    else
        return Tree_Search(x->right,k);
}
Node*Iterative_Tree_Search(Node*x, int k)
{
    while ((x != NULL) || (k != x->data))
    {
        if (k < x->data)
            x = x->left;
        else
            x = x->right;
    }
    return x;
}
Node*Tree_Minimun(Node*x)
{
    while (x->left != NULL)
        x = x->left;
    return x;
}
Node*Tree_Maxinum(Node*x)
{
    while (x->right!=NULL)
        x = x->right;
    return x;
}
void Transplant(T&tr, Node*u, Node*v)
{
    if (u->p == NULL)
        tr.root = v;
    else if (u == u->p->left)
        u->p->left = v;
    else
        u->p->right = v;
    if (v != NULL)
        v->p = u->p;
}
void Tree_Delete(T&tr, Node*z)
{
    if (z->left == NULL)
        Transplant(tr, z, z->right);
    else if (z->right == NULL)
        Transplant(tr,z,z->left);
    else
    {
        Node*y = Tree_Minimun(z->right);
        if (y->p != z)
        {
            Transplant(tr,y,y->right);
            y->right = z->right;
            y->right->p = y;
        }
        Transplant(tr,z,y);
        y->left = z->left;
        y->left->p = y;
    }
}
int main()
{
    T t;
    Node *n1 = new Node(1);
    Node *n2 = new Node(3);
    Node *n3 = new Node(2);
    Tree_Insert(t,n1);
    Tree_Insert(t,n2);
    Tree_Insert(t,n3);
    Inorder_Tree_Walk(t.root);
    cout << "\n";
    Node*s=Tree_Search(t.root,3);
    cout << s->data << endl;
    Node*min = Tree_Minimun(t.root);
    cout <<"min:\t"<< min->data << endl;
    Node*max = Tree_Maxinum(t.root);
    cout << "max:\t" << max->data << endl;
    Tree_Delete(t,n3);
    Tree_Delete(t, n1);
    Inorder_Tree_Walk(t.root);
    cout << "\n";

}

 

posted @ 2015-04-09 09:04  liuhg  阅读(186)  评论(0编辑  收藏  举报