jain12

Print Paths in a binary tree

Mar 6th, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. class Node{
  5.   public:
  6.       int data;
  7.       Node *left,*right;
  8.       Node(int key){
  9.         data=key;
  10.         left=NULL;
  11.         right=NULL;
  12.         }
  13.   };
  14.  
  15. void preorder(Node *root){
  16.   if(root==NULL)
  17.      return;
  18.   cout<<" "<<root->data;
  19.   preorder(root->left);
  20.   preorder(root->right);
  21.   }
  22.  
  23. void PrintArray(int arr[],int len){
  24.  cout<<endl;
  25.  for(int i=0;i<len;i++)
  26.     cout<<" "<<arr[i];
  27.  }
  28.  
  29. void PrintPathRecur(Node *root,int arr[],int path_len){
  30.   if(root==0)
  31.     return;
  32.   arr[path_len]=root->data;
  33.     path_len++;
  34.   if(root->left==NULL && root->right ==NULL)
  35.     PrintArray(arr,path_len);
  36.   else {
  37.     PrintPathRecur(root->left,arr,path_len);
  38.     PrintPathRecur(root->right,arr,path_len);}
  39.     }
  40.  
  41. int PrintPaths(Node *root){
  42.   int path[1000];
  43.   PrintPathRecur(root,path,0);
  44.   }
  45.  
  46. int main(){
  47.   Node *root=NULL;
  48.   Node *newnode=new Node(1);
  49.   root=newnode;
  50.   root->left=new Node(2);
  51.   root->right=new Node(3);
  52.   (root->left)->left=new Node(4);
  53.   (root->left)->right=new Node(5);
  54.   cout<<"pre order traversal ";
  55.   preorder(root);
  56.   PrintPaths(root);
  57.   return 0;
  58.   }
Add Comment
Please, Sign In to add comment