Reputation: 1
I want to find the smallest number in a rignt subtree of a node, and this code below is what I thought that was the solution, but its not working properly. What is wrong with this code?
int small; // Where the smallest value is stored
int smallest(Node n)
{
if(n.info < small && aux != 0) small = n.info;
if(aux == 0)
{
aux = 1;
small = n.dir.info;
if(n!=NULL && n.dir!=NULL) return smallest(n.dir);
}
else{
if(n.dir != NULL) return smallest(n.dir);
if(n.esq != NULL) return smallest(n.esq);
}
return small;
}
Upvotes: 0
Views: 259
Reputation: 728
I am using n.right for right subtree pointer and n.left for left subtree pointer
Just call the function smallest(n.right); smallest is a function that will find the smallest value in a binary tree
int smallest(Node n){
if( n==NULL ) return INF; // replace INF with the maximum value that int can hold in your system like 2147483647
int left_small = smallest(n.left); // smallest value in left subtree
int right_small = smallest(n.right); // smallest value in right subtree
int ans = n.info;
if( left_small < ans ) ans = left_small;
if( right_small < ans ) ans = right_small;
return ans;
}
Upvotes: 1