So I'm making a binary search tree implemented through arrays (if parent's index is i, then left child's index is (i * 2 + 1), and right child's index is (i * 2 + 2).
Whenever I'm trying to traverse the tree (pre-orderly), I'm getting a stack overflow during the 3rd pre-order function call.
Here's my code for pre-order function:
void traversePreOrder(Tree tree, int index)
{
printf("%d\n", index); //debug
if (tree.data[index].accNumber != 0) //all .accNumber values are initialized as 0
// at the start of the program to mark empty nodes.
{
printf("printing: %d\n", index); //debug
printNode(tree.data[index]);
if (tree.data[index * 2 + 1].accNumber != 0)
{
printf("will print: %d\n", index * 2 + 1); //debug
traversePreOrder(tree, index * 2 + 1);
}
if (tree.data[index * 2 + 2].accNumber != 0)
{
printf("will print: %d\n", index * 2 + 2); //debug
traversePreOrder(tree, index * 2 + 2);
}
}
else
return;
}
Here is the output of pre-order traversal:
0
printing: 0
User: Dumbledore
Account number: 53167
Account type: public
Account balance: 4597.54
Is account in debt? Yes
will print: 1
1
printing: 1
User: Stark
Account number: 13497
Account type: private
Account balance: 1549.50
Is account in debt? No
will print: 3
Process returned 255 (0xFF) execution time : 5.856 s
Press any key to continue.
The tree is supposed to look like:
(only accNumber values)
53167
/ \
13457 74310
\ / \
43158 71401 79473
/ / \
14741 69690 99751
Thank you for your help.
Update
Changing maximum tree capacity from 1000 to 50 somehow solved the problem. If somebody could explain why, that would be nice.
dataunless the index used is known to be within the limits ofdata's magnitude. Just because you have a node in your array doesn't mean both its kids are there as well. Ex: your posted tree is storable in an array of 16 nodes, Ask yourself what your code does when you recurse to examine the children of index 15. Checkingtree.data[index * 2 + 1].accNumber != 0isn't enough. Before that you need to know thatindex * 2 + 1is within0..(n-1), wherenis the magnitude ofdatain the first place.