简体   繁体   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);
}

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. OP提到代码崩溃。 Certainly this was because of the wrong leaf was traversed in if (t->r != NULL) { inorder(t->l); 当然,这是因为if (t->r != NULL) { inorder(t->l); and t->l was NULL . 并且t->lNULL

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

相关问题 使用顺序遍历删除二叉树 - Deleting a binary tree using inorder traversal C中二叉树中的有序树遍历 - Inorder tree traversal in binary tree in C 下面的二叉树中序遍历有什么问题? - What is wrong with the following binary tree inorder traversal? 使用顺序遍历在二叉树中搜索元素 - searching an element in binary tree using in order traversal 二进制搜索树的顺序遍历,显示一些错误 - Inorder traversal for binary search tree, shows some errors 我的二叉搜索树c程序有问题。我使用的是中序遍历。为什么只打印根节点? - My binary search tree c program has a problem.I am using inorder traversal.only root node printed why? 代码中的分段错误,用于查找(顺序)二叉树中节点的后继 - Segmentation fault in code for finding (inorder) successor of nodes in binary tree 二叉树的有序继承者 - Inorder Successor of Binary tree 如何按顺序显示平衡二叉树的下一个元素? (为了) - How to display the next element in sequence for a balanced binary tree? (inorder) 0 我正在研究一个 leetcode 问题:给定二叉树的根,返回其节点值的中序遍历 - 0 I'm working on a leetcode problem: Given the root of a binary tree, return the inorder traversal of its nodes' values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM