#include <string>
#include <memory>
#include <sstream>
#include <iostream>
struct node
{
using pointer = std::shared_ptr<node> ;
node( const std::string& d, const pointer& lc, const pointer& rc )
: data(d), left_child(lc), right_child(rc) {}
std::string data ;
pointer left_child ;
pointer right_child ;
};
std::ostream& write( std::ostream& stm, const node::pointer& tree )
{
if(tree)
{
stm << tree->data << ' ' ;
write( stm, tree->left_child ) ;
return write( stm, tree->right_child ) ;
}
else return stm << "# " ;
}
node::pointer make_tree( std::istream& stm )
{
std::string data ;
if( stm >> data && data != "#" )
{
auto left_child = make_tree(stm) ;
return std::make_shared<node>( data, left_child, make_tree(stm) ) ;
}
else return nullptr ;
}
int main()
{
std::istringstream stm( "root aaa C # # D # # string 1231 # # #" ) ;
auto tree = make_tree(stm) ;
write( std::cout, tree ) << '\n' ;
}
I2luY2x1ZGUgPHN0cmluZz4KI2luY2x1ZGUgPG1lbW9yeT4KI2luY2x1ZGUgPHNzdHJlYW0+CiNpbmNsdWRlIDxpb3N0cmVhbT4KCnN0cnVjdCBub2RlCnsKICAgIHVzaW5nIHBvaW50ZXIgPSBzdGQ6OnNoYXJlZF9wdHI8bm9kZT4gOwogICAgbm9kZSggY29uc3Qgc3RkOjpzdHJpbmcmIGQsIGNvbnN0IHBvaW50ZXImIGxjLCBjb25zdCBwb2ludGVyJiByYyApCiAgICAgICAgOiBkYXRhKGQpLCBsZWZ0X2NoaWxkKGxjKSwgcmlnaHRfY2hpbGQocmMpIHt9CiAgICBzdGQ6OnN0cmluZyBkYXRhIDsKICAgIHBvaW50ZXIgbGVmdF9jaGlsZCA7CiAgICBwb2ludGVyIHJpZ2h0X2NoaWxkIDsKfTsKCnN0ZDo6b3N0cmVhbSYgd3JpdGUoIHN0ZDo6b3N0cmVhbSYgc3RtLCBjb25zdCBub2RlOjpwb2ludGVyJiB0cmVlICkKewogICAgaWYodHJlZSkKICAgIHsKICAgICAgICBzdG0gPDwgdHJlZS0+ZGF0YSA8PCAnICcgOwogICAgICAgIHdyaXRlKCBzdG0s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