Example. Looking up a BST

[comp1110-2X]

To find out whether a tree contains a value, we determine what subtree of the binary search tree to descend into by comparing the desired value to the value stored in the root of the current subtree.

boolean contains(BST haystack, int needle) { if(haystack == null) { return false; } if(haystack.value == needle) { return true; } else if(haystack.value < needle) { return contains(haystack.right, needle); } else { return contains(haystack.left, needle); } }

The correctness of the function depends on the Data Invariant specified in the BST Definition, similar to the precondition on regular binary search that the array be sorted. Here, this condition is implicitly given because haystack is a BST and any argument can always be assumed to satisfy any data invariants on it.

bars magnifying-glass caret-down plus minus arrow-right xmark