二叉树(不搜索)最大功能

时间:2014-02-20 15:19:30

标签: c++ max binary-tree

我的代码出现了分段错误,我不知道为什么。我试图找到未订购的常规二叉树中的最大值。

tnode<int> *maxT(tnode<int> *t)
{
    if (t == NULL) return NULL; 

    tnode<int> *left = maxT(t->left); 
    tnode<int> *right = maxT(t->right); 

    if (left->nodeValue > right->nodeValue)
    {
        return maxT(left);
    }
    if (left->nodeValue < right->nodeValue)
    {
        return maxT(right);
    }

 }

2 个答案:

答案 0 :(得分:1)

该算法的基本原理非常简单。由于树是无序的,因此必须访问所有节点,并具有以下前提条件:

  • 空节点指针导致null作为答案。
  • 否则,没有子节点的节点将导致当前节点
  • 其他结果是节点的最大值与其子节点的最大值相比。

鉴于此,我很确定这就是你要做的事情:

template<typename T>
tnode<T>* maxT(const tnode<T>* t)
{
    if (!t)
        return nullptr;

    tnode<T>* lmax = maxT(t->left);
    tnode<T>* rmax = maxT(t->right);
    tnode<T>* cmax = (lmax && rmax) 
                   ? ((rmax->nodeValue < lmax->nodeValue ? lmax : rmax))
                   : (lmax ? lmax : rmax);
    return (!cmax || (cmax->nodeValue < t->nodeValue) ? t : cmax);
}

答案 1 :(得分:0)

tnode<int> *maxT(tnode<int> *t)
{
  if (t->right == NULL && t->left == NULL) //leaf node
    return t->nodeValue;

  else if (t->right == NULL) //no right subtree
    return MAX(t->nodeValue, maxT(t->left))

  else if (t->left == NULL) //no left subtree
    return MAX(t->nodeValue, maxT(t->right))

  else 
    return MAX(maxT(t->right), maxT(t->left));
}

在您的情况下,如果节点没有右子或左子,会发生什么。然后 node-&gt; right == NULL node-&gt; left == NULL 。但您尝试访问 left-&gt; nodeValue right-&gt; nodeValue