Searching BST

J

j_depp_99

I would like to know what would be the best way to count the nodes
accessed while searching for an item in a binary search tree. I have
to keep a tally for each item I search for. I have included my search
method from my program.
<code/>
void BinarySearchTree::find(int d)
{
//Locate the element
bool found = false;
if(isEmpty())
{
cout<<" This Tree is empty! "<<endl;
return;
}
tree_node* curr;
tree_node* parent;
curr = root;
while(curr != NULL)
{
if(curr->data == d)
{
found = true;
cout << " Item " << d << " found" << endl;

break;
}
else
{
parent = curr;
if(d>curr->data) curr = curr->right;
else curr = curr->left;
}
}
if(!found)
{
cout << " " << d <<" Data not found! "<<endl;
return;
}
if((curr->left == NULL && curr->right != NULL)|| (curr->left !=
NULL
&& curr->right == NULL))
{
if(curr->left == NULL && curr->right != NULL)
{
if(parent->left == curr)
parent->left = curr->right;
else
parent->right = curr->right;
}
else // left child present, no right child
{
if(parent->left == curr)
parent->left = curr->left;
else
parent->right = curr->left;

}
return;
}

//We're looking at a leaf node
if( curr->left == NULL && curr->right == NULL)
{
if(parent->left == curr)
parent->left = NULL;
else parent->right = NULL;
return;
}
//Node with 2 children
// replace node with smallest value in right subtree
if (curr->left != NULL && curr->right != NULL)
{
tree_node* chkr;
chkr = curr->right;
if((chkr->left == NULL) && (chkr->right == NULL))
{
curr = chkr;
curr->right = NULL;
}
else // right child has children
{
//if the node's right child has a left child
// Move all the way down left to locate smallest element

if((curr->right)->left != NULL)
{
tree_node* lcurr;
tree_node* lcurrp;
lcurrp = curr->right;
lcurr = (curr->right)->left;
while(lcurr->left != NULL)
{
lcurrp = lcurr;
lcurr = lcurr->left;
}
curr->data = lcurr->data;
lcurrp->left = NULL;
}
else
{
tree_node* tmp;
tmp = curr->right;
curr->data = tmp->data;
curr->right = tmp->right;
}

}
return;
}

</code>

Thank you. I hope my question was clear enough.
 
V

Victor Bazarov

I would like to know what would be the best way to count the nodes
accessed while searching for an item in a binary search tree. I have
to keep a tally for each item I search for. I have included my search
method from my program.
[..]

It seems that you're asking about an algorithm pertaining to
a particular data structure. Given that binary tree is basically
the same in many modern languages, I would recommend asking in
the 'comp.programming' newsgroup, where general questions on any
algorithm not language specific should be asked.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,999
Messages
2,570,243
Members
46,838
Latest member
KandiceChi

Latest Threads

Top