fork(2) download
  1. //Family Tree Example by Caner Koca for MAT 2540
  2. /*
  3. Based on the following tree:
  4.  
  5.   Adam
  6.   .____|___.______________.
  7. Ben Charlie David
  8.   | .__|__.
  9. Ed Fred Greg
  10. */
  11.  
  12.  
  13. #include <iostream>
  14. #include <string>
  15. using namespace std;
  16.  
  17. //each node will contain 4 information: name of the person
  18. //and addresses of up to 3 children
  19. class node{
  20. public:
  21. string name;
  22. node* child1;
  23. node* child2;
  24. node* child3;
  25. };
  26.  
  27.  
  28. //The following function answers the question: Is X a child of Y?
  29.  
  30. bool IsChild(node &X, node &Y){
  31. if(Y.child1==&X || Y.child2==&X || Y.child3==&X){//if the address of one of the children of Y is the address of X,
  32. cout<<X.name<<" is a child of "<<Y.name<<endl;//print a statement "X is a child of Y"
  33. return true;
  34. }
  35. else{
  36. cout<<X.name<<" is not a child of "<<Y.name<<endl;
  37. return false;
  38. }
  39. }
  40.  
  41.  
  42. int main() {
  43.  
  44.  
  45. //initializing the nodes
  46. node A,B,C,D,E,F,G;
  47.  
  48. //furnishing nodes with names
  49. A.name="Adam";
  50. B.name="Ben";
  51. C.name="Charlie";
  52. D.name="David";
  53. E.name="Ed";
  54. F.name="Fred";
  55. G.name="Greg";
  56.  
  57.  
  58. //establishing parent-child relations
  59. A.child1=&B;
  60. A.child2=&C;
  61. A.child3=&D;
  62.  
  63. C.child1=&E;
  64.  
  65. D.child1=&F;
  66. D.child2=&G;
  67.  
  68.  
  69. //checking whether the function IsChild is working properly.
  70. IsChild(B,A);
  71. IsChild(A,B);
  72. IsChild(F,D);
  73. IsChild(F,A);
  74.  
  75. return 0;
  76. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Ben is a child of Adam
Adam is not a child of Ben
Fred is a child of David
Fred is not a child of Adam