fork download
  1. #include <iomanip>
  2. #include <iostream>
  3.  
  4. class ScopedIndent
  5. {
  6. public:
  7. ScopedIndent() : _indent(_indentLevel) { _indentLevel += 4 ; }
  8. ~ScopedIndent() { _indentLevel -= 4 ; }
  9.  
  10. friend std::ostream& operator<<(std::ostream& os, const ScopedIndent& id) ;
  11.  
  12. private:
  13. unsigned _indent ;
  14. static unsigned _indentLevel ;
  15. };
  16.  
  17. unsigned ScopedIndent::_indentLevel = 0 ;
  18.  
  19. std::ostream& operator<<(std::ostream& os, const ScopedIndent& id )
  20. {
  21. return os << std::setw(id._indent) << "" ;
  22. }
  23.  
  24.  
  25. struct Node {
  26. int data;
  27. Node* left ;
  28. Node* right ;
  29.  
  30. Node(int i) : data(i), left(0), right(0) {}
  31. };
  32.  
  33.  
  34. void add( Node*& root, int num )
  35. {
  36. if ( root == 0 )
  37. {
  38. root = new Node(num) ;
  39. return ;
  40. }
  41.  
  42. if ( num < root->data )
  43. add(root->left, num) ;
  44. else
  45. add(root->right, num) ;
  46. }
  47.  
  48. void destroy(Node* root)
  49. {
  50. if (root != 0)
  51. {
  52. destroy(root->left) ;
  53. destroy(root->right) ;
  54. delete root ;
  55. }
  56. }
  57.  
  58. void inOrder( const Node* node )
  59. {
  60. ScopedIndent id ;
  61. if ( node )
  62. std::cout << id << "Begin inOrder: " << node << '\n' << id << "{\n" ;
  63. else
  64. std::cout << id << "NULL\n" ;
  65.  
  66. if ( node != 0 )
  67. {
  68. ScopedIndent id ;
  69. std::cout << id << "Left:\n" ;
  70. inOrder(node->left) ;
  71.  
  72. std::cout << '\n' << id << "Data: " << node->data << "\n\n" ;
  73.  
  74. std::cout << id << "Right:\n" ;
  75. inOrder(node->right) ;
  76. }
  77.  
  78. if ( node )
  79. std::cout << id << "}\n" ;
  80. }
  81.  
  82. int main ()
  83. {
  84. Node * root = new Node(1) ;
  85. add(root, -3) ;
  86. add(root, 2) ;
  87. add(root, 5) ;
  88.  
  89. inOrder(root) ;
  90. destroy(root) ;
  91. }
Success #stdin #stdout 0s 2984KB
stdin
Standard input is empty
stdout
Begin inOrder: 0x8e83008
{
    Left:
        Begin inOrder: 0x8e83018
        {
            Left:
                NULL

            Data: -3

            Right:
                NULL
        }

    Data: 1

    Right:
        Begin inOrder: 0x8e83028
        {
            Left:
                NULL

            Data: 2

            Right:
                Begin inOrder: 0x8e83038
                {
                    Left:
                        NULL

                    Data: 5

                    Right:
                        NULL
                }
        }
}