从二叉树中获取最大值

时间:2016-05-11 20:28:36

标签: c struct tree binary-tree

现在我是二叉树,我想从中获取最大值。考虑它如何同时具有字符串和int值,它按字母顺序排序。一切都正常工作所有插入,搜索,删除等。现在我们需要知道的是,这里有我的树。

typedef struct node 
{
    char *name;
    int count;
    struct node *l, *r; 
}*link;

如何创建一个简单的函数来查找树中最高count的内容。就像我在树中可以有20个节点并假设最高count是10并且有3个节点具有最高count。 10个最高count的数量并不重要,我只想让函数返回10.函数就像。

int maxValue(link head)
{
    //the help i need with
}

我在网上查了一下,尝试了一些例子,例如inorder和所有不同的功能,但大多数只是将所有值从左节点放到最右边的那个,所以它并没有真正帮助我找到树中的最大数量,因为我的数字从最小到最大都没有。

3 个答案:

答案 0 :(得分:1)

在这种情况下,

递归是你的朋友。您的函数会比较自身的值,左侧的最大值和右侧的最大值,并返回最大值。

int maxValue(link head)
{
    if(head == NULL){
        return -1;
    }
    int me = head->count;
    int l = maxValue(head->l);
    int r = maxValue(head->r);
    if(me >= l && me >= r) {
        return me;
    } else if(l >= me && l >= r){
        return l;
    } else {
        return r;
    }
}

<强>备注

这段代码并不像人们写的那样通用。如果count在树中始终大于等于零并且如果在开始时没有在NULL对象上调用该函数,那么它将仅按预期工作,因为那时将返回-1。在实践中更好地使用@blazs解决方案。

答案 1 :(得分:1)

我们的想法是首先计算给定节点的子树maxLeftmaxRight的最大值,然后返回max(currVal, maxLeft, maxRight),其中currVal是当前节点中的值。

以下是您在代码中直接表达的方式:

int maxValue(link head)
{
    assert(head != NULL);
    int currVal = head->count;
    if (head->l != NULL) // compute max of the left subtree
        currVal = max(currVal, maxValue(head->l));
    if (head->r != NULL) // compute max of the right subtree
        currVal = max(currVal, maxValue(head->r));
    return currVal;
}

max可以是一个简单的宏,例如

#define max(x, y) (x) > (y) ? (x) : (y)

答案 2 :(得分:0)

要在树中查找最大值,代码无法利用字母顺序。相反,需要走完整棵树。这包括检查当前节点,然后检查左右两个孩子中每个孩子的最大值。

走二叉树的一个经典改进是只回到一条腿(例如左侧)并循环另一条腿(右侧)。这个循环展开有时可以通过双腿递归的智能编译器来识别。在下面,它是明确完成的。

如果原始INT_MIN

,此代码会返回head == NULL
int maxValue(link head) {
  int max = INT_MIN;
  while (head) {
    if (head.count > max) {
      max = head.count;
    }
    int left_max = maxValue(head.left);
    if (left_max > max) { 
      max = left_max;
    }
    head = head.right;
  }
  return max;
}

样式:我宁愿看到没有*的typedef,如下所示。

typedef struct node {
    char *name;
    int count;
    struct node *l, *r; 
} link;
相关问题