我的代码出现了分段错误,我不知道为什么。我试图找到未订购的常规二叉树中的最大值。
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);
}
}
答案 0 :(得分:1)
该算法的基本原理非常简单。由于树是无序的,因此必须访问所有节点,并具有以下前提条件:
鉴于此,我很确定这就是你要做的事情:
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 。