m2skills

all paths cpp

May 15th, 2018
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.07 KB | None | 0 0
  1. // Program to print all paths from root to leaf using recursive preorder traversal
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. // node class
  7. class node{
  8. public:
  9.     int data;
  10.     int hd;
  11.     node* left;
  12.     node* right;
  13. };
  14.  
  15. // function that returns a pointer to new node
  16. node* createNode(int element){
  17.     node* temp = (node*) malloc(sizeof(node));
  18.     temp->data = element;
  19.     temp->hd = -1;
  20.     temp->left = NULL;
  21.     temp->right = NULL;
  22.     return temp;
  23. }
  24.  
  25. // function to print the path vector
  26. void printPath(vector<int> path){
  27.     for(int i=0; i<path.size(); i++){
  28.         cout<<path[i]<<" ";
  29.     }
  30.     cout<<endl;
  31. }
  32.  
  33. // function to print all paths from root to leaf using recursive preorder traversal
  34. void all_paths_from_root_to_leaf(node* current, vector<int> path){
  35.     if(current == NULL){
  36.         return;
  37.     }
  38.     // push the current node data into the path vector
  39.     path.push_back(current->data);
  40.  
  41.     // if the current node is the leaf node then we print the path and return
  42.     if(current->left == NULL && current->right == NULL){
  43.         printPath(path);
  44.         return;
  45.     }
  46.     // else we traverse deeper into the binary tree in preorder fashion
  47.     else{
  48.         all_paths_from_root_to_leaf(current->left, path);
  49.         all_paths_from_root_to_leaf(current->right, path);
  50.     }
  51. }
  52.  
  53.  
  54. int main() {
  55.  
  56.     node* head = createNode(1);
  57.     head->left = createNode(2);
  58.     head->right = createNode(3);
  59.     head->left->left = createNode(4);
  60.     head->left->right = createNode(5);
  61.     head->right->right = createNode(6);
  62.     head->left->left->right = createNode(7);
  63.     head->right->right->left = createNode(8);
  64.     head->left->left->right->left = createNode(9);
  65.     head->left->left->right->left->left = createNode(10);
  66.     head->right->right->left->right = createNode(11);
  67.     cout<<"All the paths from root to the leaf nodes are : "<<endl;
  68.     vector<int> s;
  69.     all_paths_from_root_to_leaf(head,s);
  70.  
  71. }
  72.  
  73.  
  74.  
  75. /*
  76.  
  77. All the paths from root to the leaf nodes are :
  78. 1 2 4 7 9 10
  79. 1 2 5
  80. 1 3 6 8 11
  81. Process finished with exit code 0
  82.  
  83. */
Add Comment
Please, Sign In to add comment