Мне нужно реализовать двоичное дерево на C ++, и проблема в том, что я только начал писать код на C ++. Так что я действительно новичок в этой теме, и до того, как я написал код на C или Python, а не на C ++.
Я уже создал и инициализировал бинарное дерево, дающее несколько листьев, корневой элемент дерева, и теперь я хочу посмотреть, нормально ли то, что я сделал, следовательно, это работает или это полная чушь.
Проверьте мой код, я использую Visual Studio 2017 Enterprise:
"bintree.cpp"
#include "cseatreebin.h"
#include <iostream>
using namespace std;
void main()
{
CSearchTreeBin MyTree;
std::cout << "#######################################################\n"
"##################Binary Tree C++######################\n";
MyTree.Insert(5);
MyTree.Insert(15);
MyTree.Insert(7);
MyTree.Insert(-5);
MyTree.Insert(6);
MyTree.Insert(3);
MyTree.Insert(650);
MyTree.Insert(20);
MyTree.Insert(-20);
MyTree.Insert(510);
MyTree.Print();
MyTree.Print(); cout << endl;
//cout << "Amount of Treenodes: " << MyTree.GetNrOfNodes() << endl;
// Amount/Number should be calculated again if allready called once
//cout << "Amount of Treenodes: " << MyTree.GetNrOfNodes() << endl;
// ... only if the tree has changed...
//MyTree.Insert(99);
//cout << "Number of treenodes: " << MyTree.GetNrOfNodes() << endl;
}
Пользовательский заголовочный файл:
"cseatreebin.h"
#ifndef SEARCHTREEBIN_H
#define SEARCHTREEBIN_H
class CSearchTreeBinInt;
class CSearchTreeBin
{
public:
CSearchTreeBin(void);
void Insert(int);
void Print();
private:
CSearchTreeBinInt *pInternalRep;
};
#endif // SEARCHTREEBIN_H
И мой файл инициализации двоичного дерева:
#include "cseatreebinint.h"
#include <stdlib.h>
#include <iostream>
using namespace std;
CSearchTreeBinInt::CSearchTreeBinInt()
{
pRoot = 0; //init and create treeroot
};
void CSearchTreeBinInt::Insert(int dat)
{
Insert(pRoot, dat); //insert the root to the tree
}
void CSearchTreeBinInt::Insert(Node*& rpNode, int dat)
{
if (rpNode == NULL) //check if there are nodes in the tree
{
rpNode = new Node; //create new nodes if there are none
rpNode->dat = dat;
rpNode->pLeft = rpNode->pRight = NULL;
std::cout << "Binary Tree has been initalized correctly-> inserting new Elements!\n\n";
}
else
{
if (dat < rpNode->dat) { // inserted data is less then existing?
Insert(rpNode->pLeft, dat); // put it on the left
std::cout << "A Node has been inserted on the left!\n";
}
else { // if it's bigger then already existing nodes
Insert(rpNode->pRight, dat); // put it on the right side of the tree
std::cout << "A Node has been inserted on the right side!\n";
}
}
}
И в этом файле что-то напутано, я не знаю. Я просто хочу напечатать элементы, а не всегда текстовое сообщение «Call Printfunction!», Я хочу напечатать их на консоли вывода. Графический вывод может быть сделан позже, теперь я просто хочу, чтобы он работал.
#include "cseatreebin.h"
#include "cseatreebinint.h"
#include <stdlib.h>
#include <iostream>
using namespace std;
CSearchTreeBin::CSearchTreeBin()
{
pInternalRep=new CSearchTreeBinInt; //init. and creation of Binarytree
};
void CSearchTreeBin::Insert(int dat) //dat = is this the node which will be inserted?
{
pInternalRep->Insert(dat);
}
void CSearchTreeBin::Print() {
int a;
std::cout << "Printfunction has been called!\n\n";
if (pInternalRep == NULL) return;
//CSearchTreeBin::Print(); // this won't work that easily
//pInternalRep->CSearchTreeBin::Print();
}
Каким-то образом я / мы должны найти способ напечатать содержащие элементы, если они уже находятся внутри дерева, в противном случае я должен найти ошибку, почему дерево остается пустым.
Я только начал разрабатывать на C ++, как упоминалось выше. И да, есть некоторые примеры алгоритмов BFS или что-то связанное, но ни у одного из них нет такой сложности, как у меня.