fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. struct node
  6. {
  7. int data;
  8. struct node *left;
  9. struct node *right;
  10. };
  11.  
  12. struct node* add(int x)
  13. {
  14. struct node *temp = ( struct node *) malloc(sizeof(struct node));
  15. temp->data = x;
  16. temp->left = NULL;
  17. temp->right = NULL;
  18. return temp;
  19.  
  20. };
  21.  
  22. void leave( struct node *root )
  23. {
  24.  
  25. if ( root != NULL ) {
  26.  
  27. if ( root->left == NULL && root->right == NULL ){
  28. cout << root->data << " ";
  29. }
  30. leave(root->left);
  31. leave(root->right);
  32. }
  33.  
  34. }
  35. void boundary_l( struct node *root)
  36. {
  37. if ( root != NULL ) {
  38.  
  39. if ( root->left == NULL && root->right == NULL ) {
  40. return;
  41. }
  42. cout << root->data <<" ";
  43. boundary_l(root->left);
  44. boundary_l(root->right);
  45.  
  46. }
  47. return;
  48. }
  49. void boundary_r(struct node *root)
  50. {
  51. if ( root != NULL ) {
  52.  
  53. if ( root->left == NULL && root->right == NULL ) {
  54. return;
  55. }
  56.  
  57. boundary_l(root->right);
  58. boundary_l(root->left);
  59. cout << root->data <<" ";
  60. }
  61. return;
  62.  
  63. }
  64.  
  65. void boundary( struct node *root)
  66. {
  67.  
  68. if ( root != NULL ) {
  69. cout << root->data << " ";
  70. boundary_l(root->left);
  71. leave(root->left);
  72. leave(root->right);
  73. boundary_r(root->right);
  74. }
  75.  
  76. }
  77.  
  78. int main()
  79. {
  80.  
  81. struct node *root = NULL;
  82.  
  83. root = add(1);
  84. root->left = add(2);
  85. root->right = add(3);
  86. root->left->left = add(4);
  87. root->left->right = add(5);
  88. root->right->left = add(6);
  89. root->right->right = add(7);
  90.  
  91. boundary(root);
  92. return 0;
  93. }
  94.  
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
1 2  4 5 6 7 3