given a binary search tree diagram, you need to find 4th smallest element of that tree.
For this specific problem you may do an inorder traversal of the tree.
We know inorder traversal yields elements of tree in increasing order, keep a counter
for number of elements traversed and return the fourth element.
C implementation:-
struct NODE
{
struct NODE *left;//in Java simple references would work as NODE left;
int value;
struct NODE *right;
}
int inorder(struct NODE *curr)
{
static int i=0;
if(curr->left != NULL) inorder(curr->left); /*step-1 & step-2*/
printf("%d", curr->value); /*step-3*/
i++;
if(i==4)
return curr->value;
if(curr->right != NULL) inorder(curr->right); /*step-4*/
}
C'mmon .. if you use globals or static variables . what's the use of this question !!!!
Do it without static and globals !!!
Avi
Avi Dullu's Code Arena
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks