fork(2) download
  1. #include <iostream>
  2. #include <stack>
  3.  
  4. struct leaf {
  5. public:
  6. int value;
  7. leaf* right;
  8. leaf* left;
  9. leaf* neighbor;
  10.  
  11. leaf(int v, leaf* r, leaf* l) :
  12. value(v), right(r), left(l), neighbor(nullptr) {};
  13. };
  14.  
  15. void find_neighbors(leaf* node, std::stack<leaf*> & stack)
  16. {
  17. if (node == nullptr) {
  18. return;
  19. };
  20.  
  21. if (!stack.empty()) {
  22. node->neighbor = stack.top();
  23. stack.pop();
  24. };
  25.  
  26. find_neighbors(node->right, stack);
  27. find_neighbors(node->left, stack);
  28. stack.push(node);
  29.  
  30. return;
  31. }
  32.  
  33. void show_leaf(leaf* node)
  34. {
  35. if (node == nullptr) {
  36. return;
  37. };
  38.  
  39. std::cout << "Node: " << node->value << " neighbor: " << (node->neighbor != nullptr ? node->neighbor->value : 0) << std::endl;
  40.  
  41. show_leaf(node->right);
  42. show_leaf(node->left);
  43.  
  44. return;
  45. }
  46.  
  47. int main()
  48. {
  49. leaf* tree0 = new leaf(1, nullptr, nullptr);
  50.  
  51. leaf* tree1 =
  52. new leaf(
  53. 1,
  54. new leaf(3, nullptr, nullptr),
  55. new leaf(2, nullptr, nullptr)
  56. );
  57.  
  58. leaf* tree2 =
  59. new leaf(
  60. 1,
  61. new leaf(
  62. 3,
  63. new leaf(7, nullptr, nullptr),
  64. new leaf(6, nullptr, nullptr)
  65. ),
  66. new leaf(
  67. 2,
  68. nullptr,
  69. new leaf(4, nullptr, nullptr)
  70. )
  71. );
  72.  
  73. std::stack<leaf*> stack0;
  74. find_neighbors(tree0, stack0);
  75. std::cout << "Tree #0" << std::endl;
  76. std::cout << "(1)" << std::endl;
  77. show_leaf(tree0);
  78. std::cout << std::endl;
  79.  
  80. std::stack<leaf*> stack1;
  81. find_neighbors(tree1, stack1);
  82. std::cout << "Tree #1" << std::endl;
  83. std::cout << " (1)" << std::endl;
  84. std::cout << " / \\" << std::endl;
  85. std::cout << "(2) (3)" << std::endl;
  86. show_leaf(tree1);
  87. std::cout << std::endl;
  88.  
  89. std::stack<leaf*> stack2;
  90. find_neighbors(tree2, stack2);
  91. std::cout << "Tree #2" << std::endl;
  92. std::cout << " (1)" << std::endl;
  93. std::cout << " / \\" << std::endl;
  94. std::cout << " (2) (3)" << std::endl;
  95. std::cout << " / / \\" << std::endl;
  96. std::cout << "(4) (6) (7)" << std::endl;
  97. show_leaf(tree2);
  98. std::cout << std::endl;
  99.  
  100. return 0;
  101. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
Tree #0
(1)
Node: 1 neighbor: 0

Tree #1
   (1)
  /   \
(2)   (3)
Node: 1 neighbor: 0
Node: 3 neighbor: 0
Node: 2 neighbor: 3

Tree #2
    (1)
    / \
  (2)  (3)
  /    / \
(4)  (6)  (7)
Node: 1 neighbor: 0
Node: 3 neighbor: 0
Node: 7 neighbor: 0
Node: 6 neighbor: 7
Node: 2 neighbor: 3
Node: 4 neighbor: 6