最近在学BST,打算发此贴先记录一下学习过程以及例子。
BST特点:
1.右子树大于根节点
2.左子树小于根节点
3.左右节点分别为BST
以下为插入算法的伪代码:
f(b,x){ if(b==NULL){ Init b //初始化b,并且使他左右子树都为null b->data=x //将该数据赋值给该节点 } else{ if(x>b->data) f(b->lchild,x) //如果此数据大于该节点,则让他去左子树 else f(b->rchild,x) //否则去右子树 } }
若要从小到大访问,采用中序遍历 以下为伪代码
f(b){ if(b){ f(b->lchild) cout << b->data f(b->rchild) } }
以下为一个例子:输入学生信息,根据成绩由小到大排名
#include <iostream> #include <fstream> using namespace std; ofstream out("out.txt"); ifstream in("in.txt"); struct student { string name; int id; float score; }; typedef struct BST { student data; BST *lchild, *rchild; } BST; void Insertbst(BST *&b, student datas) { if (b == NULL) { b = new BST; b->data = datas; b->lchild = b->rchild = NULL; } else { if (datas.score > b->data.score) Insertbst(b->rchild, datas); else Insertbst(b->lchild, datas); } } void output(BST *b) { if (b) { output(b->lchild); out << b->data.name << "," << b->data.id << "," << b->data.score << endl; output(b->rchild); } } int main() { int n; in >> n; student datas[n]; for (int i = 0; i < n; i++) in >> datas[i].name >> datas[i].id >> datas[i].score; BST *b = NULL; for (int i = 0; i < n; i++) { Insertbst(b, datas[i]); } output(b); system("pause"); }
输入:
6 zhao 10001 87.5 qian 10002 90.5 sun 10003 75 li 10004 94 zhou 10005 99 wu 10006 92
输出:
sun,10003,75 zhao,10001,87.5 qian,10002,90.5 wu,10006,92 li,10004,94 zhou,10005,99
2020-02-05
来源:https://www.cnblogs.com/Itukas/p/12262280.html