Binary Tree Function : TreeFindRoot. Where's the mistake?
Good morning ladies and gentlemen,
this is so far my first post. The time is around 6 am in my country and you are really my last hope, as at the moment I have run out of ideas and coffee :p, and everything seems mumbo jumbo to me. So, let's get to the point.
My source of frustration is a function I implemented to use for my binary search tree. A doubly linked binary tree like this:
Code:
typedef struct treenodeT treenodeT;
struct treenodeT
{
int id;
docnodeT *head; /* this doesn't matter at the moment */
struct treenodeT *parent;
struct treenodeT *left;
struct treenodeT *right;
};
where the root differs from the other treenodes as its parent is set to NULL. So, I have implemented around a dozen or more functions in order to make this binary tree functional, such as functions to insert/remove/search for a node etc! One of them that's been used thoroughly by the others is a function which returns the root of the tree (if any), given a pointer at a random treenode. This is it:
Code:
treenodeT *TreeFindRoot(treenodeT *treenodeP)
{
treenodeT *root;
treenodeT *hold;
root = treenodeP;
if (root == NULL) return NULL;
else
{
if (root->parent == NULL) return root;
else
{
hold = root->parent;
while (hold != NULL)
{
root = hold;
hold = hold->parent;
}
return root;
}
}
}
This function seems to work correctly most of the times called, but other times, according to the GNU debugger (which i wish to knew how to make full use of), it stucks in an endless loop when it reaches the line:
Code:
while (hold != NULL)
I have read and reread and rewritten this function 100 times with all the possible loops, and still, its getting stuck at the same point when running the program. :confused: Any ideas? Does anybody see what I cannot? Please?
Thanks in advance, especially for your patience :)
E.