HackerRank•Jun 21, 2025
Level Order Traversal
Hazrat Ali
HackerRank
In level-order traversal, nodes are visited level by level from left to right. Complete the function and print the values in a single line separated by a space.
For example:
1
\
2
\
5
/ \
3 6
\
4
For the above tree, the level order traversal is .
Input Format
You are given a function,
void levelOrder(Node * root) {
}
Nodes in the tree
Output Format
Print the values in a single line separated by a space.
Sample Input
1
\
2
\
5
/ \
3 6
\
4
Sample Output
1 2 5 3 6 4
Solution
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
class Solution {
public:
Node* insert(Node* root, int data) {
if(root == NULL) {
return new Node(data);
} else {
Node* cur;
if(data <= root->data) {
cur = insert(root->left, data);
root->left = cur;
} else {
cur = insert(root->right, data);
root->right = cur;
}
return root;
}
}
/*
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
*/
void levelOrder(Node* root) {
if (!root) return;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
Node* node = q.front();
cout << node->data << " ";
q.pop();
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
}; //End of Solution
int main() {
Solution myTree;
Node* root = NULL;
int t;
int data;
std::cin >> t;
while(t-- > 0) {
std::cin >> data;
root = myTree.insert(root, data);
}
myTree.levelOrder(root);
return 0;
}