Skip to content

Instantly share code, notes, and snippets.

@R3D9477
Created October 8, 2020 22:36
Show Gist options
  • Save R3D9477/e2fb1944069353b5396b264a5cfd2dac to your computer and use it in GitHub Desktop.
Save R3D9477/e2fb1944069353b5396b264a5cfd2dac to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
template<class T>
class BinTree
{
T _key;
bool _init;
BinTree<T> *_btLeft, *_btRight;
public:
BinTree (const T key, bool init = true): _key(key),_init(init) { }
BinTree (const BinTree& src) {
this->operator=(src);
}
virtual ~BinTree()
{
if (_btLeft) delete _btLeft;
if (_btRight) delete _btRight;
}
void addNode (const T key)
{
if (!_init) {
_key = key;
_init = true;
}
else if (key < _key) {
if (_btLeft) _btLeft->addNode(key);
else _btLeft = new BinTree(key,_init);
}
else {
if (_btRight) _btRight->addNode(key);
else _btRight = new BinTree(key,_init);
}
}
void printTree()
{
if (_btLeft) _btLeft->printTree();
cout << _key << ",";
if (_btRight) _btRight->printTree();
}
BinTree& operator= (const BinTree& src)
{
this->_key = src._key;
this->_init = src._init;
this->_btLeft = src._btLeft;
this->_btRight = src._btRight;
return (*this);
}
};
int main()
{
BinTree<int> *tree = new BinTree<int>(0, false);
for (auto i: (int[]){1,100,3,6,101,5,4})
tree->addNode(i);
tree->printTree();
cout << endl;
delete tree;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment