Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template<class ItemType>
- bool BinarySearchTree<ItemType>::contains(const ItemType& item) const {
- //inner function to find recursively thru tree, captures itself to recur.
- std::function<bool(BinaryNode<ItemType> *, const ItemType &)> finder =
- [&finder](BinaryNode<ItemType> * node, const ItemType & arg){
- //case 1: item is found
- if(node->getItem() == arg){
- return true;
- } else {
- //decide where to go next
- BinaryNode<ItemType>* direction = (arg < this->getItem()) ?
- //ternary for less than checks path AND sets direction
- [&direction, node, arg](){ if(node->getLeftChildPtr() != nullptr) direction = node->getLeftChildPtr(); }() :
- //ternary for greater than checks path AND sets direction
- [&direction, node, arg](){ if(node->getRightChildPtr() != nullptr) direction = node->getRightChildPtr(); }();
- //since we were carefull we can check direction once and recurr
- if(direction != nullptr){
- finder(direction);
- } else {
- return false;
- }
- }
- };
- return finder(this->rootPtr, item);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement