RUN


Left view and Right view of a binary tree using Iteration

For the left view, we’ll traverse each level and print the first node’s data of that level and similarly, for the right view, we’ll traverse each level and print the data of the last node in that level.

#include<bits/stdc++.h>
using namespace std;

struct Node{
	int data;
  	Node* left;
  	Node* right;
  	Node(int data){
    	this->data = data;
      	left = right = NULL;
    }
};

void printLeftAndRightViewIterative(Node* root){
	if(root == NULL) return;
	queue<Node*> q;
  	q.push(root);
  	while(!q.empty()){
    	int size = q.size();
      
      	for(int i = 0; i < size; i++){
        	Node* curr = q.front();
          	q.pop();
          	//if(i == size - 1) cout<<curr->data<<" "; //for right view
          	if(i == 0) cout<<curr->data<<" "; //for left view
          	if(curr->left) q.push(curr->left);
            if(curr->right) q.push(curr->right);
        }
    }
    
}

int main() {
/*
         1
       /    \
      2      3
    /   \   /  \
   4     5 6    7
*/
    struct Node* root = new Node(1);
  	root->left = new Node(2);
  	root->left->left = new Node(4);
  	root->left->right = new Node(5);
  	root->right = new Node(3);
  	root->right->left = new Node(6);
  	root->right->right = new Node(7);
    printLeftAndRightViewIterative(root);
    return 0;
}

 

Left view and Right view of a binary tree using Recursion

For printing the left node we will recursively call the left part of the tree and print it, and for the right view, we’ll recursively call the right part of the tree and print it.

#include<bits/stdc++.h>
using namespace std;

struct Node{
	int data;
  	Node* left;
  	Node* right;
  	Node(int data){
    	this->data = data;
      	left = right = NULL;
    }
};

void printLeftAndRightViewRecursive(Node* root){
	if(root == NULL) return;
    
  	cout<<root->data <<" ";
  	printLeftAndRightViewRecursive(root->left); // for left view
  	//printLeftAndRightViewRecursive(root->right); //for right view
}

int main() {
/*
         1
       /    \
      2      3
    /   \   /  \
   4     5 6    7
*/
    struct Node* root = new Node(1);
  	root->left = new Node(2);
  	root->left->left = new Node(4);
  	root->left->right = new Node(5);
  	root->right = new Node(3);
  	root->right->left = new Node(6);
  	root->right->right = new Node(7);
    printLeftAndRightViewRecursive(root);
    return 0;
}

Report Error/ Suggestion

Related Posts:



CopyRight © 2020

CopyRight © 2020