数据结构 二叉排序树 c++

    技术2024-08-17  58

    二叉排序树的操作

    要求:

    1.若查找成功,返回元素在有序数组中的位置和查找次数;

    2.若查找失败,返回出错标志和查找次数。

    #include <iostream> using namespace std; typedef int KeyType; typedef int InfoType; typedef struct { KeyType key; InfoType otherinfo; }ElemType; typedef struct BSTNode{ ElemType data; struct BSTNode* lchild, * rchild; }BSTNode,*BSTree;//BSTNode为节点,BSTree为结构体指针 //创建二叉排序树 void CreateBSTree(BSTree& T,KeyType e) { if (!T) { BSTree S; S = new BSTNode; S->data.key = e; S->lchild = NULL; S->rchild = NULL; T = S; } else if (e<T->data.key) { CreateBSTree(T->lchild,e); } else if (e>T->data.key) { CreateBSTree(T->rchild,e); } } int count0 = 0; //二叉排序树的查找 BSTree SearchBST(BSTree T, KeyType key) { count0++; if ((!T) || key == T->data.key) { return T; } else if(key<T->data.key) { return SearchBST(T->lchild,key); } else { return SearchBST(T->rchild, key); } } int main() { BSTree T = NULL; int n; cout << "请输入节点个数:"; cin >> n; //int a[666]; cout << "请输入节点:"; int e; for (int i = 0; i < n; i++) { cin >> e; CreateBSTree(T,e); } cout << "请输入要查找的元素:"; int key; cin >> key; BSTree address = SearchBST(T, key); if (!address) { cout << "该元素不存在,比较次数为:" << count0-1; } else { cout << "该元素的位置是" << address << ",比较次数为" <<count0<< "次"; } }
    Processed: 0.017, SQL: 9