-1

System.NullReferenceException: Object reference not set to an instance of an object

public int find(int value) {
        Node curr = root;
        while (curr != null) {
            if (curr.value == value) {
                return value;//success
            }
            if (curr.value < value) {
                curr = curr.lChild;
            }
            if (curr.value > value) {
                curr = curr.rChild;
            }
            if (curr.value == null) {
                break;
            }
        }
        return 0;//No Value
    }

I cant see whats wrong with the configuration of this binaryTree Search

Vadim Yarovikov
  • 1,811
  • 1
  • 14
  • 20
Bamuel
  • 55
  • 8

1 Answers1

0

The implementation you use does not use the fact that the cases that need to be considered are mutually exclusive. If one case is hit, an assignment might take place which destroys the precondition of the following cases. Consider the following implementation which explicitly makes the cases mutually exclusive.

public int find(int value) {
    Node curr = root;
    while (curr != null) {
        if (curr.value == value) {
            return value;
        }
        else if (curr.value < value) {
            curr = curr.lChild;
        }
        else if (curr.value > value) {
            curr = curr.rChild;
        }
        else if (curr.value == null) {
            break;
        }
    }
    return 0;
}
Codor
  • 16,805
  • 9
  • 30
  • 51
  • I do not think that it matters that much, since the *conditions* are mutually exclusive. If `curr.value < value` evaluates to true, `curr.value > value` and `curr.value == null` will necessarily evaluate to `false`, unless `curr.value` is of a custom type that overrides `>`, ` – Paul Kertscher Oct 19 '17 at 07:59
  • `else if (curr.value == null)` - can't happen. value is an `int`. – Zohar Peled Oct 19 '17 at 08:00
  • @PaulKertscher If `curr.value < value` holds, `curr` is assigned `curr.lchild`. If after the assignment `curr` is `null`, the subsequent check `curr.value == null` is dereferencing a `null` pointer; the subsequent check should have been omitted in the first place. – Codor Oct 19 '17 at 08:03