This is the correct code : #include<bits/stdc++.h>
using namespace std ;
// for creating the tree levelwise from the given string format
BinaryTreeNode<int>* levelBuildTree(string s ){
int n =s.length();
// null node case handle
int index =0 ;
BinaryTreeNode<int>* root = NULL ;
int value = s[index]-'0' ;
if (value ==-1 ){
return NULL ;
}
else if (value !=-1 ){
root = new BinaryTreeNode<int>(value);
index +=2 ;
}
queue<BinaryTreeNode<int>* > q;
q.push(root);
while (!q.empty() and index< n ){
BinaryTreeNode<int>* temp =q.front();
q.pop();
int leftData = s[index ]-'0';
if (leftData!=-1 ){
temp->left =new BinaryTreeNode<int>(leftData );
index+=2 ;
q.push(temp->left );
}
else{
temp->left = NULL ;
}
int rightData = s[index ]-'0';
if (rightData!=-1 ){
temp->right =new BinaryTreeNode<int>(rightData );
index+=2 ;
q.push(temp->right );
}
else{
temp->right=NULL ;
}
}
return root ;
}
// for printing the top view of the binary tree (MAIN LOGIC )
void printTopView (BinaryTreeNode<int>* root ){
vector<int>ans;
if (!root )return ;
map<int , int > nodes ; // 1 to one mapping
queue<pair<BinaryTreeNode<int>* , int>> q ;
q.push(make_pair(root , 0 ));
while (!q.empty()){
int n = q.size() ;
for (int i=0 ;i<n;i++){
pair<BinaryTreeNode<int>* , int>frontValue= q.front() ;
q.pop();
BinaryTreeNode<int>* frontNode = frontValue.first ;
int hd = frontValue.second ;
if (nodes.find(hd)== nodes.end()){
nodes[hd] = frontNode->data ;
}
if (frontNode->left){
q.push(make_pair(frontNode->left , hd-1 ));
}
if(frontNode->right){
q.push(make_pair(frontNode->right, hd+1 ));
}
}
}
for (auto i: nodes){
cout<<i.second<<" ";
}
cout<<endl;
}
// given input string format to tree creation
int uniqueSubstrings(string input)
{
//Step 1 : level order to binary tree creation
int index =0 ;
BinaryTreeNode<int>* root = levelBuildTree(input);
// step2 : find the topview of the binary tree
if (!root ){
cout<< "-1" ;
return 1;
}
printTopView(root);
return 1;
}