Hi, could you help me with my problem? How to make a non-recusrsive function from a recursive one? This is my recursive function (function locates the node with a specified key in binary search tree)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Key x - searched key in the tree */
/* Bvs t - pointer to the root of the tree */
/* return value - pointer to found node, NULL if the key was not found */
Position Member ( Key x, Bvs t )
{
Position pos = NULL;
if (t == NULL) return NULL;
if (t -> key == x) return (Position)t;
if (t -> key < x) pos = Member(x, t -> right);
if (t -> key > x) pos = Member(x, t -> left);
return pos;
}
So the first 2 if conditions are OK and I only have to change conditions where function Member is called? And do I not have to use labels? Sorry if my questions are stupid, but I am noob in programming...
You need to wrap all the four in a loop. You can use an infinite loop and the returns to break it.
You need to change the bodies of the last two ifs ( of course since is there that your function is recursive )
No. no it's not. What Bazzy meant by "the loop condition is wrong" isn't that it was coded wrong but that the condition of the loop excludes either of the two if statements within the loop from being met. Just assigning 'key' to 'x' still isn't working.
Then I really have no idea what should be the condition. For me, condition is met when I find x. And I thought, that when pointer t is assigned or is equel to x it should work...
I think you need to read up on how binary tree is organized before attempting this, and before asking some one else to write it for you. The code you have above should not even compile since you are trying to assign to an incompatible type, among several other issues.