c++ - Finding the minimum number in a Binary Tree recursively -


this how code looks

int main() { //root rootnode of tree     if(root!==null) {         int mini = min(root, root->data);         printf("minimum number %d", mini);     }     return 0; }  int min(node *root, int mini) {      if(root == null) {         return;     }     min(root->left, mini);     min(root->right, mini);     if(mini > root->data) {         mini = root->data;     }     return mini; } 

it doesn't give me minimum number in tree. rather, prints root node minimum.

you need use results of recursive calls instead of throwing them away.
supposed minimum values of subtrees.

the minimum value in tree minimum of

  • the root value
  • the value in left subtree, if there one
  • the value in right subtree, if there one

like this:

int min(node *root) {     int least = root->data;     if (root->left != null)     {         least = std::min(least, min(root->left));     }     if (root->right != null)     {         least = std::min(least, min(root->right));     }     return least; } 

Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -