#A binary search tree was given. Tell the 4th smallest value in it.
// traverse tree in in order, this will give the output in ascending order, take the fourth element or a[3];
int min = -1; // global variable
void traverse(NODE *p) {
static int index = -1;
// for any node, if index is 3, we have found the element do nothing
if( p == null || index == 3 )
return;
// else traverse left tree first, i.e. in order traversal
traverse( p->left );
// element found somewhere in left sub-tree
if( index == 3 )
return;
// element not found yet, use current node info
index++; min = p->info;
// traverse right sub-tree
traverse( p->right );
}
Note: not tested, suggest better methods if possible
Complexity: O(n)
Number of noded traversed depends upon the depty and the distribution of the binary tree.