fork download
  1. #include <stdio.h>
  2. #include<stdlib.h>
  3.  
  4. struct node {
  5. int data;
  6. struct node *left , *right;
  7. };
  8.  
  9. struct node* newNode(int data);
  10. void printarr(int arr[] , int l);
  11. void printpath(struct node* root);
  12. void printpathrecur(struct node* root , int path[] , int l);
  13. struct node* newNode(int data) {
  14. struct node* newn = (struct node *)malloc(sizeof(struct node));
  15. newn->left = newn->right = NULL;
  16. newn->data = data;
  17. return newn;
  18. }
  19. void printpathrecur(struct node* root , int path[] , int l) {
  20. if(root == NULL)
  21. return;
  22.  
  23. path[l] = root->data;
  24. l++;
  25. if( root->left == NULL && root->right == NULL) {
  26. printarr(path,l);
  27. }
  28. else {
  29. printpathrecur(root->left , path,l);
  30. printpathrecur(root->right , path , l);
  31. }
  32. }
  33.  
  34. void printpath(struct node* root) {
  35. int path[100];
  36. int l=0;
  37. printpathrecur(root , path , l);
  38. }
  39.  
  40. void printarr(int path[] , int l) {
  41. int i=0;
  42. for(i=0;i<l;i++) {
  43. printf("%d ",path[i]);
  44. }
  45. printf("\n");
  46. }
  47. int main(void) {
  48. struct node *root = newNode(1);
  49. root->left = newNode(2);
  50. root->right = newNode(3);
  51. root->left->left = newNode(4);
  52. root->left->right = newNode(5);
  53.  
  54. /* Print all root-to-leaf paths of the input tree */
  55. printpath(root);
  56.  
  57. return 0;
  58. }
  59.  
Success #stdin #stdout 0s 2144KB
stdin
Standard input is empty
stdout
1 2 4 
1 2 5 
1 3