データ構造とアルゴリズムの基礎 (Wang Zhuo) (29): バイナリ ソート ツリー

目次

バイナリソートツリー

前提条件:

バイナリソート検索(再帰アルゴリズム)

フレームワーク/ビルド アイデアを実行します。

プログラムの実装:

標準的な答え:

バイナリ順列ツリーへの挿入

二分順列木の削除

二分順列木の生成


バイナリソートツリー

前提条件:

#include<iostream>
using namespace std;

typedef int KeyType;
typedef int InfoType;

struct ElemType
{
    KeyType key;  //关键字
    InfoType otherinfo;  //其他数据域
};

struct BSTNode
{
    ElemType data;  //数据域
    struct BSTNode* lchild, * rchild;  //左右孩子指针
};
typedef BSTNode * BSTree;
BSTree T;  //定义二叉排序树T

バイナリソート検索(再帰アルゴリズム)

フレームワーク/ビルド アイデアを実行します。

    //ツリーが空の場合は空を返す
    //後から考えると空のツリーも二分木の一種なので空であるのは成功と同じで直接出力
    //キーとルートノードを比較
    //成功: 出力

    //失敗: 右のサブツリーを見るよりも大きく、左のサブツリーを見るよりも小さい

    // ループして操作を繰り返す

プログラムの実装:

BSTree SearchBST(BSTree T, KeyType key)
{
    //若树为空,返回空
    // 后面转念一想,空树也是这个二叉树类型,所以为空就像和成功一样,直接输出
    //比较key和根节点
    // 成功:输出
    if ((key == T->data.key) || (!T))
        return T;
    //失败:大于看右子树,小于看左子树
    else if (key > T->data.key)
    {
        T = T->rchild;
        return  SearchBST(T, key);
    }
    else if (key < T->data.key)
    {
        T = T->rchild;
        return  SearchBST(T, key);
    }
    //循环重复该操作
}

標準的な答え:

次のように入力してください。

        T = T->rchild;
        SearchBST(T, キー)を返します。

1 つのステップに結合:

         return SearchBST(T->rchild, key); //右のサブツリーで検索を続行します

BSTree SearchBST(BSTree T, KeyType key)
{
    if ((key == T->data.key) || (!T))
        return T;
    else if (key > T->data.key)
        return SearchBST(T->lchild, key);
    else
        return SearchBST(T->rchild, key);
}

バイナリ順列ツリーへの挿入

//二叉排列树的插入
void InsertBSTree(BSTree& T, ElemType& e)
{
    if (!T)
    {
        T =new BSTNode;
        T->data = e;
    }

    if (T->data.key == e.key);
    //已有该元素,退出
    else if (e.key > T->data.key)
        InsertBSTree(T->rchild, e);
    else if (e.key < T->data.key)
        InsertBSTree(T->lchild, e);
}

二分順列木の削除

より複雑な


二分順列木の生成

// 二叉排列树的生成
void CreatBSTree(BSTree & T)
{
    //输入序列(也可以从形参传入)
    cout << "input info about the tree" << endl;
    vector<ElemType> vec;
    ElemType input;
    while (cin >> input.key)
    {
        vec.push_back(input);
    }
    //调用插入算法
    for (vector<ElemType>::iterator it = vec.begin(); it != vec.end(); ++it)
    {
        InsertBSTree(T, *it);
    }
}

おすすめ

転載: blog.csdn.net/Zz_zzzzzzz__/article/details/130161267