简体   繁体   中英

Binary Tree (not search) max function

I'm getting a segmentation fault with my code and I'm not sure why. I'm trying to find the max value in a regular binary tree that is not ordered.

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);
    }

 }

The fundamentals of the algorithm are fairly straight forward. Because the tree is unordered, all nodes must be visited, with the following preconditions:

  • A null node pointer results in null as an answer.
  • Else a node with no children results in the current node
  • Else result is the max of the node compared to the max of its children.

Given that, I'm pretty sure this is what you're trying to do:

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);
}
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));
}

In your case, what happens if a node doesn't have a right or left child. Then either node->right == NULL or node->left == NULL . Yet you are trying to access left->nodeValue or right->nodeValue .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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