fork download
  1. //
  2. // main.cpp
  3. // Root to leaf path
  4. //
  5. // Created by Himanshu on 08/02/22.
  6. //
  7.  
  8. #include <iostream>
  9. #include <queue>
  10. using namespace std;
  11.  
  12. struct TreeNode {
  13. int val = 0;
  14. struct TreeNode *left, *right;
  15. };
  16.  
  17. TreeNode* newNode(int data)
  18. {
  19. TreeNode* Node = new TreeNode();
  20. Node->val = data;
  21. Node->left = NULL;
  22. Node->right = NULL;
  23.  
  24. return(Node);
  25. }
  26.  
  27.  
  28. void solve(TreeNode* root, vector<string>& paths, string s) {
  29. if (root == NULL) {
  30. return;
  31. } else {
  32. if (root->left == NULL && root->right == NULL) {
  33. paths.push_back(s + to_string(root->val));
  34. }
  35. solve(root->left, paths, s + to_string(root->val) + "->");
  36. solve(root->right, paths, s + to_string(root->val) + "->");
  37. }
  38.  
  39. }
  40.  
  41.  
  42. int main() {
  43. TreeNode *root = newNode(3);
  44. root->left = newNode(9);
  45. root->right = newNode(20);
  46. root->right->left = newNode(15);
  47. root->right->right = newNode(7);
  48.  
  49. vector<string> paths;
  50. string s = "";
  51.  
  52. cout<<"Paths from root to leaf are: "<<endl;
  53. solve(root, paths, s);
  54.  
  55. for (int i=0; i<paths.size(); i++) {
  56. cout<<paths[i]<<endl;
  57. }
  58.  
  59. return 0;
  60. }
  61.  
Success #stdin #stdout 0.01s 5504KB
stdin
Standard input is empty
stdout
Paths from root to leaf are: 
3->9
3->20->15
3->20->7