繁体   English   中英

使用有序遍历在二叉树中查找最大元素

[英]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);
}

我正在尝试实现有序遍历以在二叉树中找到最大元素。 我编写的代码似乎没有返回结果。 顺便说一句,我使用的最大变量被声明为全局变量,并初始化为零。 谁能告诉我我要去哪里错了? 先谢谢你!

max=t->value; 无条件设置值。 @戴维·范·赖恩

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提到代码崩溃。 当然,这是因为if (t->r != NULL) { inorder(t->l); 并且t->lNULL

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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