Why is my print function wrong?
#include<iostream>
#include<queue>
using namespace std;
class node{
public:
int data;
node *left;
node *right;
// constructor
node(int d){
data = d;
left = NULL;
right = NULL;
}
};
node *build_tree(int pre[], int i, int in[], int s, int e){
// base case
if(s>e){
return NULL;
}
// rec case
node *root = new node(pre[i]);
int index = -1;
for(int j=s; j<=e; j++){
if(in[j] == pre[i]){
index = j;
break;
}
}
i++;
root->left = build_tree(pre,i,in,s,index-1);
root->right = build_tree(pre,i,in,index+1,e);
return root;
}
void print(node *root){
queue<node *> q;
q.push(root);
while(!q.empty()){
// if front of the queue == -1, pop it
while(q.front()->data == -1){
q.pop();
}
if(q.empty()){
break;
}
// push left and right children
if(q.front()->left == NULL){
q.push(new node(-1));
}
else{
q.push(q.front()->left);
}
if(q.front()->right == NULL){
q.push(new node(-1));
}
else{
q.push(q.front()->right);
}
// print leftChild
if(q.front()->left != NULL){
cout<<q.front()->left->data<<" => ";
}
else{
cout<<"END => ";
}
// print root
cout<<q.front()->data;
// print rightChild
if(q.front()->right != NULL){
cout<<" <= "<<q.front()->right->data;
}
else{
cout<<" <= END";
}
cout<<endl;
q.pop();
}
}
int main() {
int n;
cin>>n;
int pre[10000];
for(int i=0; i<n; i++){
cin>>pre[i];
}
int m;
cin>>m;
int in[10000];
for(int i=0; i<m; i++){
cin>>in[i];
}
node *root = build_tree(pre,0,in,0,m-1);
print(root);
return 0;
}