#include <string>
#include <sstream>
#include <iostream>
struct node
{
node( const std::string& d, node* lc, node* rc )
: data(d), left_child(lc), right_child(rc) {}
~node() { delete left_child ; delete right_child ; }
std::string data ;
node* left_child ; // unique owning pointer
node* right_child ; // unique owning pointer
private: node( const node& ) ; void operator= ( const node& ) ; // non-copyable
};
std::ostream& write( std::ostream& stm, node* tree )
{
if(tree)
{
stm << tree->data << ' ' ;
write( stm, tree->left_child ) ;
return write( stm, tree->right_child ) ;
}
else return stm << "# " ;
}
node* make_tree( std::istream& stm )
{
std::string data ;
if( stm >> data && data != "#" )
{
/*auto*/ node* left_child = make_tree(stm) ;
return new node( data, left_child, make_tree(stm) ) ;
}
else return 0 ;
}
int main()
{
std::istringstream stm( "root aaa C # # D # # string 1231 # # #" ) ;
/*auto*/node* tree = make_tree(stm) ;
write( std::cout, tree ) << '\n' ;
delete tree ;
}
I2luY2x1ZGUgPHN0cmluZz4KI2luY2x1ZGUgPHNzdHJlYW0+CiNpbmNsdWRlIDxpb3N0cmVhbT4KCnN0cnVjdCBub2RlCnsKICAgIG5vZGUoIGNvbnN0IHN0ZDo6c3RyaW5nJiBkLCBub2RlKiBsYywgbm9kZSogcmMgKQogICAgICAgIDogZGF0YShkKSwgbGVmdF9jaGlsZChsYyksIHJpZ2h0X2NoaWxkKHJjKSB7fQoKICAgIH5ub2RlKCkgeyBkZWxldGUgbGVmdF9jaGlsZCA7IGRlbGV0ZSByaWdodF9jaGlsZCA7IH0KCiAgICBzdGQ6OnN0cmluZyBkYXRhIDsKICAgIG5vZGUqIGxlZnRfY2hpbGQgOyAvLyB1bmlxdWUgb3duaW5nIHBvaW50ZXIKICAgIG5vZGUqIHJpZ2h0X2NoaWxkIDsgLy8gdW5pcXVlIG93bmluZyBwb2ludGVyCgogICAgcHJpdmF0ZTogbm9kZSggY29uc3Qgbm9kZSYgKSA7IHZvaWQgb3BlcmF0b3I9ICggY29uc3Qgbm9kZSYgKSA7IC8vIG5vbi1jb3B5YWJsZQp9OwoKc3R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