fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct node
  5. {
  6. int data;
  7. struct node* left;
  8. struct node* right;
  9. };
  10.  
  11. void printPathsRecur(struct node* node, int path[], int pathLen);
  12. void printArray(int ints[], int len);
  13. void printPaths(struct node* node)
  14. {
  15. int path[1000];
  16. printPathsRecur(node, path, 0);
  17. }
  18.  
  19. void printPathsRecur(struct node* node, int path[], int pathLen)
  20. {
  21. if (node==NULL)
  22. return;
  23. path[pathLen] = node->data;
  24. pathLen++;
  25. if (node->left==NULL && node->right==NULL)
  26. {
  27. printArray(path, pathLen);
  28. }
  29. else
  30. {
  31. printPathsRecur(node->left, path, pathLen);
  32. printPathsRecur(node->right, path, pathLen);
  33. }
  34. }
  35. void printArray(int ints[], int len)
  36. {
  37. int i;
  38. for (i=0; i<len; i++)
  39. {
  40. printf("%d ", ints[i]);
  41. }
  42. printf("\n");
  43. }
  44. struct node* newnode(int data)
  45. {
  46. struct node* node = (struct node*)
  47. malloc(sizeof(struct node));
  48. node->data = data;
  49. node->left = NULL;
  50. node->right = NULL;
  51.  
  52. return(node);
  53. }
  54. int main()
  55. {
  56.  
  57. /* Constructed binary tree is
  58.   6
  59.   / \
  60.   3 5
  61.   / \ /
  62.   2 5 4
  63.   /\
  64.   7 4
  65.  
  66.   */
  67.  
  68. struct node *root = newnode(6);
  69. root->left = newnode(3);
  70. root->right = newnode(5);
  71. root->left->left = newnode(2);
  72. root->left->right = newnode(5);
  73. root->left->right->left=newnode(7);
  74. root->left->right->right=newnode(4);
  75. root->right->left = newnode(4);
  76.  
  77. printPaths(root);
  78.  
  79. getchar();
  80. return 0;
  81. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
6 3 2 
6 3 5 7 
6 3 5 4 
6 5 4