What is wrong in the below code of printing Right View of a binary tree using the Queue data structure?
#include <iostream>
#include <queue>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int val) : data(val), left(nullptr), right(nullptr) {}
};
void printRightView(Node* root) {
if (root == nullptr) return;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int n = q.size();
for (int i = 0; i < n; i++) {
Node* x = q.front();
q.pop();
if (i == n - 1) {
cout << x->data << " ";
}
if (x->left) {
q.push(x->left);
}
if (x->right) {
q.push(x->right);
}
}
}
}
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
void printRightView(struct Node* root) {
if (root == NULL) return;
struct Node** queue = (struct Node**)malloc(100 * sizeof(struct Node*));
int front = 0, rear = 0;
queue[rear++] = root;
while (front < rear) {
int n = rear - front;
for (int i = 0; i < n; i++) {
struct Node* x = queue[front++];
if (i == n - 1) {
printf("%d ", x->data);
}
if (x->left) {
queue[rear++] = x->left;
}
if (x->right) {
queue[rear++] = x->right;
}
}
}
free(queue);
}
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
Node(int val) {
data = val;
left = right = null;
}
}
public class Main {
public static void printRightView(Node root) {
if (root == null) return;
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int n = q.size();
for (int i = 0; i < n; i++) {
Node x = q.poll();
if (i == n - 1) {
System.out.print(x.data + " ");
}
if (x.left != null) {
q.add(x.left);
}
if (x.right != null) {
q.add(x.right);
}
}
}
}
}
from collections import deque
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def printRightView(root):
if root is None:
return
q = deque([root])
while q:
n = len(q)
for i in range(n):
x = q.popleft()
if i == n - 1:
print(x.data, end=' ')
if x.left:
q.append(x.left)
if x.right:
q.append(x.right)
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
function printRightView(root) {
if (root === null) return;
let q = [root];
while (q.length) {
let n = q.length;
for (let i = 0; i < n; i++) {
let x = q.shift();
if (i === n - 1) {
process.stdout.write(x.data + ' ');
}
if (x.left) q.push(x.left);
if (x.right) q.push(x.right);
}
}
}
We have not initialized anything in the Queue
Queue will never be empty.
left and right nodes of the tree are null.
None
This question is part of this quiz :
Top MCQs on Queue Data Structure with Answers