关于二叉查找树(Binary Search Tree)的介绍可以看一下我的这篇文章:
https://blog.csdn.net/Jifu_M/article/details/112827685
项目介绍
- 本项目实现BST排序并测试它的正确性。
- 被读取txt文件包含一系列整数值。读取它们并按照读取它们的顺序构造一个二叉搜索树。因此,读取的第一个数字将是树的根。
- 在构建树的过程中,您不需要平衡它。
- 当把最后一个值读入BST时,进行序遍历以升序输出值
- 在5个字符宽的字段中每一行打印10个值。
- 不使用STL或其他库来实现BST。
被读取的txt如下图所示:
代码实现
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int c_number = 0;
struct Node
{
int value;
Node* left;//left: ^tree_node
Node* right;//right: ^tree_node
};
Node* root = NULL;
Node* find(int value, Node* node)
{
if (node == NULL)//if value == nil then return not found
return NULL;
if (value == node->value){//if value == node.contents then return node
return node;
}
else if (value < node->value){//else if value < node.contents then find(value, node.left)
find(value, node->left);
}
else{//find(value, node.right)
find(value, node->right);
}
}
void insert(int value, Node* node){
Node* next;//next: ^tree_node, left: boolean
bool left;
if (value == node->value){//if value == node.contents then return
return;
}
else if (value < node->value){//else if value < node.contents then next = node.left; left = true
next = node->left;
left = true;
}
else{//else next = node.right; left = false
next = node->right;
left = false;
}
if (next != NULL){//if next != nil then insert(value, next)
insert(value, next);
}
else{
next = new Node;// make a new node
next->value = value;// store the value
next->right = NULL;
next->left = NULL;
if (left){// update the parent
node->left = next;
}
else{
node->right = next;
}
}
}
Node* insert_first(int value)
{
Node* start = new Node;
start->value = value;
start->left = NULL;
start->right = NULL;
return start;
}
void visit(Node* tree_node)
{
if (tree_node->left != NULL){//if node.left != nil then visit(node.left)
visit(tree_node->left);
}
cout << setw(5)<<tree_node->value;//print(node.contents)
c_number++;
if (c_number%10 == 0){//Print the values 10 to a line in a 5‐character wide field.
cout << " "<<endl;
}
if (tree_node->right != NULL){//if node.right != nil then visit(node.right)
visit(tree_node->right);
}
}
int main()
{
ifstream read;
string a;
cout << "Please enter the filename: " << endl;
cin >>a;
read.open(a.c_str());
if (!read){
cout << "Can't open file" << endl;
exit(1);
}
while (!read.eof()){
int tool;
read >> tool;
root = insert_first(tool);//root = insert_first(item)
int i = 1;
while(i < 999)
{
if (read.fail())break;
read >> tool;
insert(tool, root);//insert(item, root)
i++;
}
visit(root);//visit(root)
}
read.close();
return 0;
}
输出结果如下图: