DAA: Algorithm of Right View of a Binary Tree

Algorithm of Right View of a Binary Tree

The right view of a binary tree is the visible nodes from the right side of the tree.

Algorithm of Right View of a Binary Tree

In the given tree, the visible nodes from the right side are one, three, and six. Hence the right view is 1 3 6.

In other words, we can say that the right view of a binary tree contains the last nodes at each level.

How can we approach this problem?

Approach 1

Recursion can be a great help to solve this problem. Keep track of each level and maximum level. Now we will traverse in a way such that the right subtree is traversed before the left subtree. Whenever we strike a node whose level is more than the maximum level so far, we print the last node in its level.

C++ code:

 #include <bits/stdc++.h>
 using namespace std;
 // Create tree Structure
 struct Node {
     int data; // Value of the tree Node
     struct Node *left, *right; // Left and right pointer to the node
 };
 // Allocate memory to the newely created node 
 struct Node* newNode(int item)
 {
     struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); // Allocate //memory
     temp->data = item; // Insert the data
     temp->left = temp->right = NULL; // The right and left of current child is NULL
     return temp; // return currrent node
 }
 // The function will print the right view nodes of binary tree
 void right_View_Util(struct Node* root,  int level, int* max_level)
 {
     //If we reach the last level
     if (root == NULL)
         return;
     //If currrent max is less than level
     if (*max_level < level) {
         cout << root->data << "\t"; // print last node
         *max_level = level; // Make it as currrent max.
     }
     // Recurisvley call for the left and right subtrees
     right_View_Util(root->right, level + 1, max_level);
     right_View_Util(root->left, level + 1, max_level);
 }
 // Helper for Right View funtion
 void right_View(struct Node* root)
 {
     int max_level = 0; // initlaise max level as 0
     right_View_Util(root, 1, &max_level);
 }
 int main() // Main function
 {
     struct Node* root = newNode(1); //create root node
     root->left = newNode(2); // create left node
     root->right = newNode(3); // create right node
     root->left->left = newNode(4); // left child of left node
     root->left->right = newNode(5); // right child of left node
     root->right->left = newNode(6); // left child of right parent node
     root->right->right = newNode(7); // right child of right parent node
     root->right->left->right = newNode(8);
     right_View(root);
     return 0;
 } 

C Code:

 #include <stdio.h>
 #include <stdlib.h>
 // Create tree Structure
 struct Node {
     int data; // Value of the tree Node
     struct Node *left, *right; // Left and right pointer to the node
 };
 // Allocate memory to the newely created node
 struct Node* newNode(int item)
 {
     struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); // Allocate memory
     temp->data = item; // Insert the data
     temp->left = temp->right = NULL; // The right and left of current child is NULL
     return temp; // return currrent node
 }
 // The function will print the right view nodes of binary tree
 void right_View_Util(struct Node* root, int level, int* max_level)
 {
     //If we reach the last level
     if (root == NULL)
         return;
     //If currrent max is less than level
     if (*max_level < level) {
         printf("%d\t", root->data); // print last node
         *max_level = level; // Make it as currrent max.
     }
     // Recurisvley call for the left and right subtrees
     right_View_Util(root->right, level + 1, max_level);
     right_View_Util(root->left, level + 1, max_level);
 }
 // Helper for Right View funtion
 void right_View(struct Node* root)
 {
     int max_level = 0; // initlaise max level as 0
     right_View_Util(root, 1, &max_level);
 }
 int main() // Main function
 {
     struct Node* root = newNode(1); //create root node
     root->left = newNode(2); // create left node
     root->right = newNode(3); // create right node
     root->left->left = newNode(4); // left child of left node
     root->left->right = newNode(5); // right child of left node
     root->right->left = newNode(6); // left child of right parent node
     root->right->right = newNode(7); // right child of right parent node
     root->right->left->right = newNode(8);
     right_View(root);
     return 0;
 } 

Output:

1        3        7        8

Approach 2

This approach will use a queue data structure, do level order traversal, and print the tree’s rightmost node.

C++ code:

 #include <bits/stdc++.h>
 using namespace std;
 // Create tree Structure
 struct Node {
     int data; // Value of the tree Node
     struct Node *left, *right; // Left and right pointer to the node
 };
 // Allocate memory to the newly created node
 struct Node* newNode(int item)
 {
     struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); // Allocate //memory
     temp->data = item; // Insert the data
     temp->left = temp->right = NULL; // The right and left of current child is NULL
     return temp; // return currrent node pointer
 }
 void right_View(Node* root) // This will print the right view of the binary tree
 {
     if (!root) // If tree is empty we return
         return;
     // Delcare  a queue of Node Structure
     queue<Node*> q;
     q.push(root); // Push the root in the queue
     while (!q.empty()) // Iterate in the queue
     {
         int n = q.size(); // here n is number of node at current level
         // Loop through all the nodes in the level
         for (int i = 1; i <= n; i++) {
             Node* temp = q.front(); // Take front node from the queue
             q.pop(); // pop the front node from the queue
             if (i == n) // if we reach the last node print the data of last node
                 cout << temp->data << "\t";
             // If the left node exist push in queue
             if (temp->left != NULL)
                 q.push(temp->left);
             // If the right node of the current level exist push in queue
             if (temp->right != NULL)
                 q.push(temp->right);
         }
     } // Run the loop until all level is traversed
 }
 int main() // Main function
 {
     struct Node* root = newNode(1); //create root node
     root->left = newNode(2); // create left node
     root->right = newNode(3); // create right node
     root->left->left = newNode(4); // left child of left node
     root->left->right = newNode(5); // right child of left node
     root->right->left = newNode(6); // left child of right parent node
     root->right->right = newNode(7); // right child of right parent node
     root->right->left->right = newNode(8);
     right_View(root);
     return 0;
 } 

Output:

1        3        7        8

Time complexity: O(n) where n is the nodes in the binary tree

Space complexity: O(n), where n is the number of nodes in the binary tree


Related Topics

DAA: Interpolation Search Algorithm

Interpolation Search Algorithm There is no doubt that binary search is a great algorithm with average time complexity of log n. The feature of discarding one half of the array reduces...

4 minutes read.

DAA: Depth-First Search Algorithm

Depth-first search: DFS is a traversing algorithm of a graph or tree in which one node is taken as arbitrary, and with the help of that arbitrary node, all its...

6 minutes read.

DAA: Bottom view of a Binary Tree

Bottom view of a Binary Tree The bottom view of a binary tree is the number of nodes visible when viewed from the bottom. At every horizontal distance, there would be...

3 minutes read.

DAA: Rabin Karp Algorithm

Rabin Karp Algorithm The Rabin Karp or Karp Rabin algorithm is used to matching a specific pattern in the string. It uses the technique of hashing to match a specific text. There also...

6 minutes read.

DAA: Bead Sort Algorithm

Bead Sort Algorithm The bead sort is also known as the gravity sort algorithm. The algorithm is based on the natural phenomena of gravity. The phenomenon is the falling of things...

3 minutes read.

DAA: Density of a Binary Tree Algorithm

The Density of a Binary Tree Algorithm The density of a binary tree is defined as the ratio of the tree’s size to the tree’s height.  The height of the tree is...

2 minutes read.

DAA: Insertion Sort Algorithm on Singly Link List

Insertion Sort Algorithm on Singly Link List We will sort a singly link list using the bubble sort technique. Example: Input : 20->30->40->10 Output :10->20->30->40 Input : 20->4->3 Output : 3->4->20 Sorting Technique The insertion sort technique works...

3 minutes read.

DAA: Breadth First Search (BFS) for a Graph

Breadth First Search (Bfs) For A Graph The algorithm in which all the graph nodes are traversed is known as the breadth-first search algorithm. In this algorithm, we select one node,...

5 minutes read.

DAA: Binary Tree and its Categories

Binary Tree and its Categories The binary tree is a non-linear data structure in which there are 0 or utmost 2 nodes.  Each node has two children, i.e., left and right...

4 minutes read.

DAA: Floyd Cycle Detection

Floyd Cycle Detection Floyd Cycle algorithm is one of the cycle detection algorithms to detect the cycle in a given singly linked list. In the Floyd Cycle algorithm, we have two pointers...

4 minutes read.

DAA: Insert a node in Binary Search Tree

Insert a node in Binary Search Tree (BST) We have a Binary search tree and a key. Insert the key in the binary search tree if not present. In the above figure,...

4 minutes read.

DAA: Algorithm to Find the Maximum Width of a Tree

Algorithm to Find the Maximum Width of a Tree The width of a binary tree is defined as the maximum number of nodes at a given level. The level having the...

5 minutes read.

Symmetric Trees in DAA

Symmetric Trees The trees that are mirror images of themselves are known as symmetric trees. Look at the following tree image below: The tree is symmetric as the left subtree is the mirror...

4 minutes read.

DAA: Application of DFS and BFS

Application of DFS and BFS Depth-first search and breadth-first searches are the most famous algorithms used in daily life and the programming world. Let us now explore each application in which...

3 minutes read.

DAA: Bubble Sort Algorithm

Bubble Sort Algorithm The bubble sort algorithm is also known as the sinking algorithm. In this algorithm, we iterate over the array, and it takes two adjacent elements and swaps them...

3 minutes read.

DAA: Find the Height or Maximum Depth of a Binary Tree

Find the Height or Maximum Depth of a Binary Tree We have a binary tree structure and we need to find its height. It is defined by the distance from the...

3 minutes read.

DAA: Continuous Tree

Continuous Tree A continuous tree is the one in which the nodes from root to leaf path, the two adjacent node values, have a difference of 1. Input :          3                     /   \                   ...

5 minutes read.

DAA: Bubble Sort Algorithm on Linked List

Bubble Sort Algorithm on Linked List In this article, we will sort a Link List using the bubble sort technique. Example: Input : 20->30->40->10 Output :10->20->30->40 Input : 20->4->3 Output : 3->4->20 Sorting Technique The bubble sort technique...

4 minutes read.

DAA: KMP Algorithm

KMP ALGORITHM The KMP algorithm is abbreviated as the "Knuth Morris Pratt” algorithm. This algorithm was developed by all of them.  This algorithm searches a pattern of length m in a string...

10 minutes read.

Invert Binary Tree in DAA

Invert Binary Tree: A binary tree is a tree in which each node of the tree contains two children, i.e., left children and right children. Let us suppose we have...

2 minutes read.