初学数据结构---动态查找之二叉排序树

#include <iostream>
#include <string>
using namespace std;


typedef int KeyType;
typedef struct
{
    KeyType key;
} DataType;

typedef struct Node
{
    DataType data;
    struct Node *lchild, *rlchild;
}BiTreeNode,*BiTree;

//二叉排序树查找
BiTree BSTSearch(BiTree T, DataType x)
{
    BiTreeNode *p;
    if(T != NULL)
    {
        p = T;
        while(p != NULL)
        {
            if(p->data.key == x.key)
                return p;
            else if(x.key < p->data.key)
                p = p->lchild;
            else p = p->rlchild;
        }
    }
    return NULL;
}

//二叉排序树插入

bool BSTInsert(BiTree *T, DataType x)
{
    BiTreeNode *p, *cur, *parent = NULL;
    cur = *T;
    while(cur != NULL)
    {
        if(cur->data.key == x.key)
        {
            return false;
        }
        parent = cur;
        if(x.key < cur->data.key)
            cur = cur->lchild;
        if(x.key > cur->data.key)
            cur = cur->rlchild;
    }
    p = new BiTreeNode;
    if(!p)
        return false;
    p->data = x;
    p->lchild = NULL;
    p->rlchild = NULL;
    if(!parent)
        *T = p;
    else
        if(x.key < parent->data.key)
            parent->lchild = p;
        else
            parent->rlchild = p;
    return true;
}

//中序遍历算法
void InorderTrverse(BiTree T)
{
    if(T)
    {
        InorderTrverse(T->lchild);
        cout << T->data.key << " ";
        InorderTrverse(T->rlchild);
    }
}
int main()
{
    BiTree T = NULL, p;
    DataType table[] = { 37,32,35,62,82,95,73,12,5 };
    int n = sizeof(table) / sizeof(table[0]);
    DataType x = { 73 };
    int i;
    for(i = 0;i < n;i++)
    {
        BSTInsert(&T, table[i]);
    }
    cout << "中序遍历序列为:" << endl;
    InorderTrverse(T);
    cout << "***                 ***" << endl;
    p = BSTSearch(T, x);
    cout << p->data.key << endl;

    return 0;
}

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/Mr_Ming_/article/details/73135738
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞