Table of contents
Binary sort search (recursive algorithm)
Insertion into a binary permutation tree
Deletion of binary permutation tree
Generation of binary permutation tree
Binary Sort Tree
Preconditions:
#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
Binary sort search (recursive algorithm)
Run the framework/build idea:
//If the tree is empty, return empty
//After thinking about it later, the empty tree is also the type of binary tree, so being empty is the same as success, directly output
//Compare key and root node
//Success: output//Failure: greater than looking at the right subtree, less than looking at the left subtree
// loop to repeat the operation
Program implementation:
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);
}
//循环重复该操作
}
standard answer:
Just put:
T = T->rchild;
return SearchBST(T, key);
combined into one step:
return SearchBST(T->rchild, key); //Continue to search in the right subtree
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);
}
Insertion into a binary permutation tree
//二叉排列树的插入
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);
}
Deletion of binary permutation tree
more complex
Generation of binary permutation tree
// 二叉排列树的生成
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);
}
}