jain12

print left view of a binary tree

Feb 29th, 2020
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. #include<iostream>
  2. #include<queue>
  3. using namespace std;
  4.  
  5. class Node{
  6.   public:
  7.       int data;
  8.       Node *left,*right;
  9.       Node(int key){
  10.         data=key;
  11.         left=NULL;
  12.         right=NULL;
  13.         }
  14.   };
  15.  
  16. void PrintLeftView(Node *root){
  17. if(root==NULL)
  18.   return ;
  19. queue<Node*>q;
  20. q.push(root);
  21. q.push(NULL);
  22. cout<<" "<<root->data;
  23. while(!q.empty()){
  24.   Node *temp=q.front();
  25.   q.pop();
  26.   if(temp!=NULL){
  27.     if(temp->left!=NULL)
  28.         q.push(temp->left);
  29.     if(temp->right!=NULL)
  30.         q.push(temp->right);
  31.     }
  32.   else
  33.     if(q.size()>0){
  34.         q.push(NULL);
  35.         temp=q.front();
  36.         cout<<" "<<temp->data;
  37.         }
  38.     }
  39. }
  40.  
  41. int main(){
  42.   Node *root=NULL;
  43.   Node *newnode=new Node(1);
  44.   root=newnode;
  45.   root->left=new Node(2);
  46.   root->right=new Node(3);
  47.   (root->left)->left=new Node(4);
  48.   (root->right)->right=new Node(5);
  49.   ((root->left)->left)->left=new Node(6);
  50.   PrintLeftView(root);
  51.   return 0;
  52.   }
Add Comment
Please, Sign In to add comment