fork(5) download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <iomanip>
  4. using namespace std;
  5.  
  6. template <typename KeyT, typename ValueT>
  7. class Node
  8. {
  9. public:
  10. Node(KeyT k, ValueT v)
  11. {
  12. key = k;
  13. value = v;
  14. right = NULL;
  15. left = NULL;
  16. }
  17.  
  18. Node<KeyT, ValueT> * lowest()
  19. {
  20. Node<KeyT, ValueT> * v = this;
  21.  
  22. if (right != NULL)
  23. if (v->value > left->value) v = left;
  24. if (left != NULL)
  25. if (v->value > right->value) v = right;
  26.  
  27. return v;
  28. }
  29.  
  30. Node<KeyT, ValueT> * searchByKey(KeyT k)
  31. {
  32. if (key == k)
  33. return this;
  34.  
  35. Node<KeyT, ValueT> * n = NULL;
  36.  
  37. if (left != NULL)
  38. n = left->searchByKey(k);
  39. if (n != NULL) return n;
  40. if (right!= NULL)
  41. n = right->searchByKey(k);
  42. if (n != NULL) return n;
  43.  
  44. return NULL;
  45. }
  46.  
  47. Node<KeyT, ValueT> * getRight()
  48. {
  49. return right;
  50. }
  51.  
  52. Node<KeyT, ValueT> * getLeft()
  53. {
  54. return left;
  55. }
  56.  
  57. void setRight(Node<KeyT, ValueT> * nright)
  58. {
  59. right = nright;
  60. }
  61.  
  62. void setLeft(Node<KeyT, ValueT> * nleft)
  63. {
  64. left = nleft;
  65. }
  66.  
  67. KeyT getKey()
  68. {
  69. return key;
  70. }
  71.  
  72. ValueT getValue()
  73. {
  74. return value;
  75. }
  76.  
  77. private:
  78. KeyT key;
  79. ValueT value;
  80.  
  81. Node<KeyT, ValueT> * right;
  82. Node<KeyT, ValueT> * left;
  83. };
  84.  
  85. int main(int c, char * v[])
  86. {
  87. Node<int, int> * tree = new Node<int, int>(4, 6);
  88. tree->setRight(new Node<int, int>(6, 7));
  89. tree->setLeft(new Node<int, int>(2, 8));
  90.  
  91. Node<int, int> * result = NULL;
  92.  
  93. result = tree->lowest();
  94. cout << setw(16) << "Lowest: " << "Key:" << result->getKey() << " Value:" << result->getValue() << endl;
  95.  
  96. result = tree->searchByKey(2);
  97. cout << setw(16) << "By key 2: " << "Key:" << result->getKey() << " Value:" << result->getValue() << endl;
  98. }
Success #stdin #stdout 0.02s 2860KB
stdin
Standard input is empty
stdout
        Lowest: Key:4 Value:6
      By key 2: Key:2 Value:8