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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
#include <iostream>
#include <string>
#include <sstream>
#include <memory>
#include <map>
struct Foo {
int data {0};
int left {-1};
int right {-1};
};
std::istream & operator>> ( std::istream & in, Foo & ff ) {
in >> ff.data >> ff.left >> ff.right;
return in;
}
struct Del {
template <class T>
void operator()(T* p) {
std::cout << "[deleted #" << ( p ? p->data : 0 ) << "]\n";
delete p;
}
};
struct Bar {
int data {0};
std::unique_ptr<Bar,Del> lef;
std::unique_ptr<Bar,Del> rig;
};
void print( const std::unique_ptr<Bar,Del> & node )
{
if ( node ) {
print( node->lef );
std::cout << ' ' << node->data;
print( node->rig );
}
}
int main ()
{
std::string input = "4 2 1 6 3 -1 8 4 5 9 -1 -1 10 -1 -1 3 -1 -1";
std::istringstream IN( input );
std::map<int,std::pair<Bar*,bool>> list;
std::unique_ptr<Bar,Del> root;
int row = 0;
Foo entry;
while ( IN >> entry ) {
if ( 0 == row ) {
root.reset( new Bar );
Bar * node = root.get();
node->data = entry.data;
std::cout << row << " [created #" << entry.data << ']';
if ( 0 <= entry.left ) list.emplace( entry.left, std::make_pair( node, true) );
if ( 0 <= entry.right ) list.emplace( entry.right, std::make_pair( node, false) );
}
else {
auto it = list.find( row );
if ( list.end() != it ) {
if ( it->second.second ) {
it->second.first->lef.reset( new Bar );
Bar * node = it->second.first->lef.get();
node->data = entry.data;
std::cout << row << " [created #" << entry.data << ']';
if ( 0 <= entry.left ) list.emplace( entry.left, std::make_pair( node, true) );
if ( 0 <= entry.right ) list.emplace( entry.right, std::make_pair( node, false) );
} else {
it->second.first->rig.reset( new Bar );
Bar * node = it->second.first->rig.get();
node->data = entry.data;
std::cout << row << " [created #" << entry.data << ']';
if ( 0 <= entry.left ) list.emplace( entry.left, std::make_pair( node, true) );
if ( 0 <= entry.right ) list.emplace( entry.right, std::make_pair( node, false) );
}
list.erase( it );
}
}
std::cout << " list size " << list.size() << '\n';
++row;
}
std::cout << "final list size " << list.size() << "\n\n";
print( root );
std::cout << "\n\n";
return 0;
}
|