Sunday, July 12, 2015

Left and Right View of a Binary Tree

Left View

Left view of a Binary Tree is set of nodes visible when a tree is seen from left side. 

The following are the steps :
1.Do level order.
2.Print the first node in every level.

                                                                             Figure 1

The figure above shows the nodes(marked with red arrow) that are seen from left side of the tree.

Code for printing the left view nodes:
 void LeftViewoftree(struct node* root) {

 if (root == NULL) return ;
 queue<node *> q;
 cout<<root->data<<" ";
 int flag=0;
 q.push(root);
 q.push(NULL);
 while (!q.empty()) {
  struct node *curr = q.front();
  q.pop();
  if (curr == NULL) {
     if (!q.empty()){
   q.push(NULL);
   flag=1;
  }

  }

  else {
   if(flag==1){
   cout<<curr->data<<" ";
   flag=0;
   }
   if (curr->left != NULL){       
   q.push(curr->left);
       
   }
   if (curr->right != NULL){
   q.push(curr->right);
   
   }
  }
          }
}

No comments:

Post a Comment