我制作了一个程序,该程序插入值,使用二进制搜索对它们进行排序,然后输出排序后的值。但是,我也想使用函数PrintTree()来打印树。我想不出任何方法来实现该功能中的功能代码。 到目前为止,这是我的代码。
#ifndef b_h
#define b_h
#include <iostream>
class BSTNode
{
public:
int Key;
BSTNode * Left;
BSTNode * Right;
BSTNode * Parent;
int Height;
};
class BST
{
private:
BSTNode * root;
BSTNode * insertKey(BSTNode * node, int newKey);
void PrintTreeInOrder(BSTNode * node);
BSTNode * hasKey(BSTNode * node, int searchKey);
public:
BST();
~BST();
void insertKey(int newKey);
void PrintTreeInOrder();
bool hasKey(int searchKey);
void TreePrint();
};
#endif
上面的头文件。
#include "b.h"
BST::BST() : root(NULL)
{
}
BSTNode * BST::insertKey(BSTNode * node, int newKey)
{
if(node == NULL)
{
node = new BSTNode;
node->Key = newKey;
node->Left = NULL;
node->Right = NULL;
node->Parent = NULL;
}
else if(node->Key < newKey)
{
node->Right = insertKey(node->Right, newKey);
node->Right->Parent = node;
}
else
{
node->Left = insertKey(node->Left, newKey);
node->Left->Parent = node;
}
return node;
}
void BST::insertKey(int newKey)
{
root = insertKey(root, newKey);
}
void BST::PrintTreeInOrder(BSTNode * node)
{
if(node == NULL)
return;
PrintTreeInOrder(node->Left);
std::cout << node->Key << " ";
PrintTreeInOrder(node->Right);
}
void BST::PrintTreeInOrder()
{
PrintTreeInOrder(root);
std::cout << std::endl;
}
BSTNode * BST::hasKey(BSTNode * node, int key)
{
if (node == NULL)
return NULL;
else if(node->Key == key)
return node;
else if(node->Key < key)
return hasKey(node->Right, key);
else
return hasKey(node->Left, key);
}
bool BST::hasKey(int searchKey)
{
BSTNode * result = hasKey(root, searchKey);
return result == NULL ?
false :
true;
}
上面的cpp文件。
#include <cstddef>
#include <iostream>
#include <vector>
#include <limits>
#include "b.h"
using namespace std;
int main()
{
cout << "Binary Search Tree" << endl;
BST * tree = new BST;
cout << "Enter the numbers to be stored (end with a letter): ";
int value;
int i = 0;
vector <int> keys;
cin >> value;
while (!cin.fail()){
keys.push_back(value);
cin >> value;
i++;
}
cin.clear(); // reset failbit
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
for(const int& key : keys){
tree->insertKey(key);}
int number;
cout << "Which number do you want to look up? " <<endl;
cin >> number;
bool b = tree->hasKey(number);
if(b){
cout << number << " is in the tree: yes";}
else{
cout << number << " is in the tree: no";
cout << endl;}
cout << "The numbers in sorted order: ";
tree->PrintTreeInOrder();
tree->TreePrint();
return 0;
}
主要。
该程序有效,它使用二进制搜索对向量进行排序,并具有“搜索关键字”功能,但是,我想在函数PrintTree()中打印树;如下所示;
8
3 10
1 6 14
4 7 13
有人可以帮忙吗?