I am coding to print out BST preorder and postorder traversals.
The class tree is defined like this
class BinSearchTree{
char symbol;
BinSearchTree *lChild;
BinSearchTree *rChild;
public:
BinSearchTree(char letter) { symbol = letter;lChild = NULL; rChild = NULL;}
BinSearchTree() { symbol = '0';}
BinSearchTree* buildTree(BinSearchTree *tree, char letter);
void printTreePreOrder (BinSearchTree *temp, std::ofstream &fp1);
void printTreeInOrder (BinSearchTree *temp, std::ofstream &fp1);
};
I have used a simple recursion to create the BST
BinSearchTree* BinSearchTree::buildTree(BinSearchTree *tree, char letter){
if (tree == NULL) {
tree = new BinSearchTree (letter);
return tree;
}
else {
if (letter<(tree->symbol))
{
tree->lChild = (BinSearchTree*) buildTree(tree->lChild, letter);
return tree;
}
else{
tree->rChild = (BinSearchTree*) buildTree(tree->rChild, letter);
return tree;
}
}
return tree;
}
But when I print out the traversal, I am getting segmentation faults. I use this piece of code for preorder and something similar for postorder
void BinSearchTree::printTreePreOrder (BinSearchTree *temp, std::ofstream &fp1) {
if (temp == NULL){
return;
}
else{
fp1 << symbol << " ";
printTreePreOrder(lChild, fp1);
printTreePreOrder(rChild, fp1);
}
}
In my main code, I create my tree using
T = new BinSearchTree(str[0]);
for(i=1; i<num; i++){
fp >> str[i];
T->buildTree(T,str[i]);
}
and do traversal using
T->printTreePreOrder(T,fp1)
I have been trying to figure out the error since days and I think am committing a silly error. Any help is appreciated.
PS - Working on Ubuntu 14.04 and using G++ compiler.