fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <cstdio>
  4. #include <stdlib.h>
  5. using namespace std;
  6.  
  7. struct node
  8. {
  9. int data;
  10. struct node* left;
  11. struct node* right;
  12. };
  13.  
  14. struct node* newNode(int data)
  15. {
  16. struct node* new_node=(struct node*)malloc(sizeof(struct node));
  17. new_node->data=data;
  18. new_node->left=NULL;
  19. new_node->right=NULL;
  20. return new_node;
  21. }
  22.  
  23. void path(struct node* node,vector<vector<int> > &res,vector<int> &s)
  24. {
  25.  
  26. if(node==NULL) return;
  27. s.push_back(node->data);
  28.  
  29.  
  30. if(node->left==NULL && node->right==NULL)
  31. res.push_back(s);
  32.  
  33.  
  34. else
  35. {
  36. path(node->left,res,s);
  37. path(node->right,res,s);
  38. }
  39. s.pop_back();
  40. }
  41. int main() {
  42.  
  43. struct node* root = newNode(1);
  44. root->left= newNode(2);
  45. root->right= newNode(3);
  46. root->left->left= newNode(4);
  47. root->left->right= newNode(5);
  48. vector<vector<int> >res;
  49. vector<int> s;
  50. path(root,res,s);
  51. for(int i=0;i<res.size();i++)
  52. {
  53. for(int j=0;j<res[i].size();j++)
  54. {
  55. cout<<res[i][j]<<"\t";
  56. }
  57. cout<<"\n";
  58. }
  59. return 0;
  60. }
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
1	2	4	
1	2	5	
1	3