fork(1) download
  1. #include <iostream>
  2. #include <iomanip>
  3.  
  4. struct Binode
  5. {
  6. char data ;
  7. Binode* r ;
  8. Binode* l ;
  9. };
  10.  
  11. struct Indent {
  12. static unsigned level ;
  13.  
  14. Indent() { std::cout << std::setw(level) << "" << "{\n"; level += 4 ; }
  15. ~Indent() { level -=4 ; std::cout << std::setw(level) << "" << "}\n" ; }
  16. };
  17.  
  18. std::ostream& operator<<(std::ostream& os, const Indent & indent)
  19. {
  20. return os << std::setw(Indent::level) << "" ;
  21. }
  22.  
  23. unsigned Indent::level = 0 ;
  24.  
  25. unsigned depth(Binode* p)
  26. {
  27. Indent indent ;
  28. std::cout << indent ;
  29.  
  30. if ( p == nullptr )
  31. {
  32. std::cout << "NULL\n" ;
  33. return 0 ;
  34. }
  35. std::cout << p->data << '\n' ;
  36.  
  37. std::cout << indent << p->data << ": right node\n" ;
  38. unsigned rdepth = depth(p->r) ;
  39. std::cout << indent << "rdepth: " << rdepth << '\n' ;
  40.  
  41. std::cout << indent << p->data << ": left node\n" ;
  42. unsigned ldepth = depth(p->l) ;
  43. std::cout << indent << "ldepth: " << ldepth << '\n' ;
  44.  
  45. std::cout << indent << "Returning: " << (rdepth < ldepth ? 1+ldepth : 1+rdepth) << '\n' ;
  46. return rdepth < ldepth ? 1+ldepth : 1+rdepth ;
  47. }
  48.  
  49. int main()
  50. {
  51. Binode a { 'a', nullptr, nullptr };
  52. Binode b { 'b', &a, nullptr } ;
  53. Binode c { 'c', &b, nullptr } ;
  54.  
  55. std::cout << depth(&c) << '\n' ;
  56. }
Success #stdin #stdout 0s 2852KB
stdin
Standard input is empty
stdout
{
    c
    c: right node
    {
        b
        b: right node
        {
            a
            a: right node
            {
                NULL
            }
            rdepth: 0
            a: left node
            {
                NULL
            }
            ldepth: 0
            Returning: 1
        }
        rdepth: 1
        b: left node
        {
            NULL
        }
        ldepth: 0
        Returning: 2
    }
    rdepth: 2
    c: left node
    {
        NULL
    }
    ldepth: 0
    Returning: 3
}
3