Touching back with the main rules:
The array val[8] = {-1,4,2,1,3,6,5,7} is initialized.
The array bst[] is initialized to -1.
Writing two functions for a BST and preOrder traversal with arrays, the rules of the game are the parameters for the call functions must be: (val[i] is using a loop)
Code:
addBST(0,val[i]);
preOrder(0);
I came up with some solutions, but they're the most intellectually devoid solutions I have ever come up with. I seem to have a mental road block before me. Does anyone have any problem solving solutions to make this code more efficient?
Also, any suggestions on how to alter the program if the call parameters for root had to be "1" instead of "0"? Thanks in advance, friends.
Code:
void addBST(int root,int newNode)
{
if (newNode < 0)
{bst[root] = val[root+1]; return; }
if (newNode == val[root+1])
{return;}
if (newNode < bst[root])
{
if (bst[(root)*2+1] == -1)
{ bst[(root)*2+1] = newNode; return;}
else
addBST(((root)*2+1), newNode);
}
if (newNode > bst[root])
{
if (bst[(root)*2+2] == -1)
{ bst[(root)*2+2] = newNode; return;}
else
addBST(((root)*2+2), newNode);
}
return;
}
void preOrder(int root)
{
if (bst[root])
{
if (bst[root] != -1)
{
printf(" %d ", bst[root]);
preOrder((root*2+1));
preOrder((root*2+2));
}
}
}