1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
#include <iostream>
#include <vector>
#include <set>
struct Node {
int data = 0 ;
Node* right = nullptr ;
Node* left = nullptr ;
};
namespace detail {
// flags: flags[i] == true if values[i] was found
// invariant: values.size() <= flags.size()
// cnt: count of the elements in vector values found so far
static void IsPresent( const Node* pn, const std::vector<int>& values,
std::vector<bool>& flags, std::size_t& cnt )
{
for( std::size_t i = 0 ; i < values.size() ; ++i )
if( pn->data == values[i] ) { flags[i] = true ; ++cnt ; }
if( cnt < values.size() && pn->left ) IsPresent( pn->left, values, flags, cnt ) ;
if( cnt < values.size() && pn->right ) IsPresent( pn->right, values, flags, cnt ) ;
}
}
// return vector of flags. flags[i] == true if values[i] is present
std::vector<bool> IsPresent( const Node* pn, const std::vector<int>& values ) {
std::vector<bool> flags( values.size() ) ; // initialised to all false
std::size_t cnt = 0 ;
if(pn) detail::IsPresent( pn, values, flags, cnt ) ;
return flags ;
}
int main()
{
Node tree[] { {0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10} };
{
// build a toy tree for testing
const auto link = [&tree] ( int i, int r, int l )
{ tree[i].right = tree+r ; tree[i].left = tree+l ; };
link( 0, 1, 2 ) ;
link( 1, 3, 4 ) ;
link( 2, 5, 6 ) ;
link( 3, 7, 8 ) ;
link( 4, 9, 10 ) ;
}
auto result = IsPresent( tree, { 2, 20, 3, 30, 4, 40, 5, 50, 8, 80, 9 } ) ;
for( bool f : result ) std::cout << f << ' ' ; // 1 0 1 0 1 0 1 0 1 0 1
std::cout << '\n' ;
result = IsPresent( tree, { 0, 6, 5, 2 } ) ;
for( bool f : result ) std::cout << f << ' ' ; // 1 1 1 1
std::cout << '\n' ;
}
| |