I am trying to create my own Binary Tree data structure.
I am using a BinaryNode<T>
class as the leaves with a BinaryNode<T>*
root to keep track of the root node.
template<class T>
class PPBinaryTree {
private:
BinaryNode<T>* root;
public:
PPBinaryTree();
bool add(T Data, BinaryNode<T>* Root);
T* search(T Data, BinaryNode<T>* Root);
};
Here is the implementation of the add
function. No matter what I try I cannot create any new branches. The RootProbe
seems to be a copy of the branch pointers so when I assign Data
to it nothing changes in the branch.
The only solution I can think of is to change the line
RootProbe = (new BinaryNode<T>(Data));
to
*RootProbe = *(new BinaryNode<T>(Data));
but that just makes my program crash with an unhandled exception.
template<class T>
bool PPBinaryTree<T>::add(T Data, BinaryNode<T>* Root){
bool isSuccessful = false;
BinaryNode<T>* RootProbe;
if(Root == NULL){
Root = new BinaryNode<T>(Data);
this->setRoot(Root);
isSuccessful = true;
return isSuccessful;
}
else{
while(RootProbe != NULL){
if(Data > Root->getData())
RootProbe = Root->getRightBranch();
else
RootProbe = Root->getRightBranch();
}
RootProbe = (new BinaryNode<T>(Data));
isSuccessful = true;
return isSuccessful;
}
}
Here is the BinaryNode
class:
template<class S>
class BinaryNode {
private:
S data;
BinaryNode *leftBranch;
BinaryNode *rightBranch;
public:
BinaryNode(S data);
void setData(S data);
S getData( );
void setLeftBranch(BinaryNode newNode);
BinaryNode* getLeftBranch( );
void setRightBranch(BinaryNode newNode);
BinaryNode* getRightBranch( );
};