Reputation: 445
how can I Write a code with these requirements? this is the question: check if there is a node with key K in the tree T, and if so, return a reference to this node. If the tree is empty, report that the node was not found and stop. Otherwise, compare K with the key value of the root node X.
This is what i found:
public GenBT<T> Find(GenBT<T> k, T inf){
if (k == null) return null;
else
switch (inf.CompareTo(k.inf)){
case 1: return Find(k.RT, inf);
case -1: return Find(k.LT, inf);
case 0: return k;
default: return null;}
};
but I also found that if I want to search or find in BST I have to use a code like this :
struct node* search(int data){
struct node *current = root;
printf("Visiting elements: ");
while(current->data != data){
if(current != NULL) {
printf("%d ",current->data);
//go to left tree
if(current->data > data){
current = current->leftChild;
} //else go to right tree
else {
current = current->rightChild;
}
//not found
if(current == NULL){
return NULL;
}
}
}
return current;
}
These two look very different and I don't know which way is right and in general what is the right way of solving this question
Upvotes: 0
Views: 1239
Reputation: 36371
To transform the recursive solution to an iterative one we need to insert a loop. In the recursive case we change the node parameter for each recursion. To do the same in the iterative case we simply create a variable that is updated instead of doing a recursion.
Changed naming to make a clearer and compilable example. Note also that CompareTo can return any number, not just 0, 1, -1. So a switch is insufficient:
public class Node<T>
{
public Node<T> Left { get; }
public Node<T> Right { get; }
public T Value { get; }
public Node(Node<T> left, Node<T> right, T value)
=> (Left, Right, Value) = (left, right, value);
}
public static Node<T> Find<T>(Node<T> root, T target) where T : IComparable<T>
{
var current = root;
while (current != null)
{
var comparison = target.CompareTo(current.Value);
if (comparison > 0)
current = current.Right;
else if (comparison < 0)
current = current.Left;
else
return current;
}
return null;
}
See also how to transform a recursive method to an iterative one in a more generic way. Note that the example uses a stack, In your case a stack is not needed, since you only process one branch of the tree.
Upvotes: 2