I am trying to write a function that will return the next smallest element key greater than the parameter q when called in a binary balanced tree The code works fine up to the point when no values greater than q is found in the first parts of left nodes of the tree,which means that I have to go check the nodes on the right and the test code gives me the following, I don't understand which part has gone wrong.
Prepared trees; now start test1
next larger key after 10 should be 12, instead found 131075
next larger key after 20 should be 22, instead found 131075
next larger key after 30 should be 32, instead found 131075
next larger key after 60 should be 62, instead found 131075
next larger key after 70 should be 72, instead found 131075
Press any key to continue . . .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
int find_next_larger(tree_node_t *tree, int q)
{
//return base null tree
if (tree->left == NULL)
return q;
else
{
tree_node_t * tmp_node;
tree_node_t * right_node_of_path[10000];
int i = 0;
tmp_node = tree;
//if the tree has right node, run through the entire tree starting from left
while (tmp_node->right != NULL)
{
right_node_of_path[i] = tmp_node;
i++;
if (q < tmp_node->key)
{
tmp_node = tmp_node->left;
}
else
{
tmp_node = tmp_node->right;
}
}
if (tmp_node->key > q)
return tmp_node->key;
else
{
while (i >= 0)
{
tmp_node = right_node_of_path[i];
i--;
}
tmp_node = tmp_node->right;
while (tmp_node->right != NULL)
tmp_node = tmp_node->left;
return tmp_node->key;
}
}
}
|