fork(2) download
  1. #include <string>
  2. #include <memory>
  3. #include <sstream>
  4. #include <iostream>
  5.  
  6. struct node
  7. {
  8. using pointer = std::shared_ptr<node> ;
  9. node( const std::string& d, const pointer& lc, const pointer& rc )
  10. : data(d), left_child(lc), right_child(rc) {}
  11. std::string data ;
  12. pointer left_child ;
  13. pointer right_child ;
  14. };
  15.  
  16. std::ostream& write( std::ostream& stm, const node::pointer& tree )
  17. {
  18. if(tree)
  19. {
  20. stm << tree->data << ' ' ;
  21. write( stm, tree->left_child ) ;
  22. return write( stm, tree->right_child ) ;
  23. }
  24. else return stm << "# " ;
  25. }
  26.  
  27. node::pointer make_tree( std::istream& stm )
  28. {
  29. std::string data ;
  30. if( stm >> data && data != "#" )
  31. {
  32. auto left_child = make_tree(stm) ;
  33. return std::make_shared<node>( data, left_child, make_tree(stm) ) ;
  34. }
  35. else return nullptr ;
  36. }
  37.  
  38. int main()
  39. {
  40. std::istringstream stm( "root aaa C # # D # # string 1231 # # #" ) ;
  41. auto tree = make_tree(stm) ;
  42. write( std::cout, tree ) << '\n' ;
  43. }
  44.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
root aaa C # # D # # string 1231 # # #