prakharvk

Pre Order binary tree build and print

Jun 7th, 2019
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.64 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. class node {
  4.     public:
  5.     int data;
  6.     node *left;
  7.     node *right;
  8.    
  9.     node(int d){
  10.         data=d;
  11.         left=NULL;
  12.         right=NULL;
  13.     }
  14. };
  15.  
  16. node* buildTree(){
  17.  
  18.     int data;
  19.     cin>>data;
  20.     if(data==-1)
  21.         return NULL;
  22.     node *curr= new node(data);
  23.     curr->left=buildTree();
  24.     curr->right=buildTree();
  25.     return curr;
  26. }
  27.  
  28. void print(node *curr){
  29.     if(curr==NULL)
  30.         return;
  31.        
  32.     cout<<curr->data<<" ";
  33.     print(curr->left);
  34.     print(curr->right);
  35. }
  36.  
  37. int main() {
  38.    
  39.     node *curr=buildTree();
  40.     print(curr);
  41.     return 0;
  42. }
Add Comment
Please, Sign In to add comment