简体   繁体   中英

Finding the maximum element in a Binary tree using an inorder traversal

void inorder(struct btnode *t)
{
    if (root == NULL)
    {
        printf("No elements in a tree to display");
        return;
    }
    max=t->value;
    if (t->l != NULL) 
    {
    inorder(t->l);
    if(max<t->value)
        {
        max=t->value;   
        }
    }   

    if (t->r != NULL)    
    {
    inorder(t->l);
    if(max<t->value)
        {
        max=t->value;   
        }
    }   
    printf("max=%d\n",max);
}

I am trying to implement an inorder traversal to find the maximum element in a binary tree. The code that I have written doesn't seem to return a result. By the way, the max variable i used, was declared as a global variable and initialized at zero. Can anyone tell me where I'm going wrong here? Thank you before hand!

max=t->value; sets value with no condition. @David van rijn

void inorder(const struct btnode *t) {
    if (root == NULL) {
        printf("No elements in a tree to display");
        return;
    }
    if(max<t->value) {  // Add test
      max=t->value;
    }
    if (t->l != NULL) {
      inorder(t->l);
    }   
    if (t->r != NULL) {
      // inorder(t->l);  Wrong leaf.
      inorder(t->r);
    }   
    // Best to print from calling routine
    // printf("max=%d\n",max);
}

void foo(const struct btnode *t) {
  max = INT_MIN;  // Set to minimum `int` value.
  inorder(t);
  printf("max=%d\n",max);
}

OP mentioned that code crashes. Certainly this was because of the wrong leaf was traversed in if (t->r != NULL) { inorder(t->l); and t->l was NULL .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM