Code Review: How can I simplify this simple method?

I have the following simple way to do a full binary tree search. I can definitely say that this can be simplified, but it does not come to me.

bool Node::lookup(int d)
{
    if (data==d)
    {
        return true;
    }
    else
    {
        if (left != NULL && right != NULL)
        {
            return left->lookup(d) && right->lookup(d);
        }
        else if (left != NULL)
        {
            return left->lookup(d);
        }
        else if (right != NULL)
        {
            return right->lookup(d);
        }
        else
        {
            return false;
        }
    }
}
+3
source share
6 answers
bool Node::lookup(int d)
{
    return (data==d)
        || ((NULL != left) && left->lookup(d))
        || ((NULL != right) && right->lookup(d));
}

It takes advantage of short circuit behavior &&and ||.

Note that this is not exactly equivalent to your code, but I suggest that this is probably the behavior you really want. (Your source code returns false, both children exist, but dnot in both of them.)

+10
source

, :

bool Node::lookup(int d) 
{ 
    return 
        (data==d) || 
        (
            (right || left) &&
            (!left || left->lookup(d)) &&
            (!right || right->lookup(d))
        ); 
} 

, , lookup true, d left, right, > left right

+1

ifs else ifs

bool Node::lookup(int d)
{
    if (data==d)
        return true;
    if (left != NULL && right != NULL)
        return left->lookup(d) && right->lookup(d);
    if (left != NULL)
        return left->lookup(d);
    if (right != NULL)
        return right->lookup(d);
    return false;
}
0

:

bool Node::lookup(int d)
{
  if (data==d)
    return true;

  if (left == right)
    return left == null ? false : left->lookup(d) && right->lookup(d);   
  return left == null ? right->lookup(d) : left->lookup(d);
}
0
bool Node::lookup(int d)
{
    return (data == d)
       || (left && left->lookup(d))
       || (right && right->lookup(d));    
}

, , , , .

0

.

bool Node::lookup(int d){
    if (!this) // a little bit unorthodox, but much more elegant that testing before call
        return false;
    return (data == d) || left->lookup(d) || right->lookup(d);
}

EDIT: , - . ? , , :

Node* tree; 
if (tree->lookup(i)) // we encapsulate in the Node class the information that an empty tree must return false
    printf("found!\n");

Node* tree; 
if (tree && tree->lookup(i)) // we have to know in the outside that a NULL tree shall return false
    printf("found!\n");

The only way he could create UB is when the compiler considers that thisit cannot be NULL and skip the test. This will not happen because in the wild there is enough code that uses this type of validation. Also, in simple C, this is common practice.

-4
source

Source: https://habr.com/ru/post/1772205/


All Articles