a
/ \
a a
/ \ / \
a c a f
/ \ / \
b d e g
I have a tree that looks like the above, represented by a linked structure:
class Node
{
Node* leftChild;
Node* rightChild;
char data;
}
class Tree
{
Node* root;
}
My goal is to find all the paths from the root to leaf nodes.
My tree traversal algorithm looks like this:
void inorder()
{
in(root);
}
void in(CharNode* currentNode)
{
if(currentNode)
{
in(currentNode->leftChild);
cout << currentNode->data << endl;
in(currentNode->rightChild);
}
}
When I run this, I am positive that the tree is being built as shown. I have tested that. I cannot, however, figure out why my tree traversal segmentation faults.
The output I get is :
b
Segmentation fault.
I have tested it on trees with smaller heights, and it works. But for some reason it doesn’t work on a trees with heights larger than 2. I thought it was something going wrong with the tree, I have gone through and printed each parent, left child, and right child and they print out as shown. So it’s definitely the traversal algorithm.
As you build your tree, be sure to initialize leftChild and rightChild to NULL (0) on your nodes. This is critical for leaf-nodes and for nodes missing either a leftChild or a rightChild.