Advertisement
Guest User

ayy lmao

a guest
Jan 23rd, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1.  
  2. template<class ItemType>
  3. bool BinarySearchTree<ItemType>::contains(const ItemType& item) const {
  4.  
  5.   //inner function to find recursively thru tree, captures itself to recur.
  6.   std::function<bool(BinaryNode<ItemType> *, const ItemType &)> finder =
  7.     [&finder](BinaryNode<ItemType> * node, const ItemType & arg){
  8.     //case 1: item is found
  9.     if(node->getItem() == arg){
  10.       return true;
  11.     } else {
  12.  
  13.       //decide where to go next
  14.       BinaryNode<ItemType>* direction = (arg < this->getItem()) ?
  15.       //ternary for less than checks path AND sets direction
  16.       [&direction, node, arg](){ if(node->getLeftChildPtr() != nullptr) direction = node->getLeftChildPtr();  }() :
  17.       //ternary for greater than checks path AND sets direction
  18.       [&direction, node, arg](){ if(node->getRightChildPtr() != nullptr) direction = node->getRightChildPtr();  }();
  19.  
  20.  
  21.       //since we were carefull we can check direction once and recurr
  22.       if(direction != nullptr){
  23.         finder(direction);
  24.       } else {
  25.         return false;
  26.       }
  27.     }
  28.   };
  29.  
  30.   return finder(this->rootPtr, item);
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement